简体   繁体   中英

jquery Return ajax response and user defined variable to function

I am having an issue passing in a defined variable to a function from an ajax call. What should happen is on click of an element, it should pass the text of the clicked element to the function, do an ajax call which has nothing to do with the defined variable, return the variable and the data from the call to another function that renders the elements. When I get to the function that renders the html content, the variable is now undefined.

My question is how can I send the ajax response data and a user defined variable that has no correlation to the ajax call to another function?

My JSON function:

function getJSONP(url, data) {
  return $.ajax(url, {
    dataType: 'json',
    data: data
  });
}

My click event:

$('.day').on('click', function() {
  getTimes($(this).text());
});

My first function that does the ajax (this is where the selector returns a value):

function getTimes(selector) {
  console.log(selector);
  var eventDate = selector;

  getJSONP(CAL_API_URL).then(function(data) {
    data = _.valuesIn(data)[5][0];
    return data;
  }).then(appendTimes(eventDate));
}

My 2nd function that renders the HTML (here the selector is undefined):

function appendTimes(dates, selector) {
  console.log(selector);

  _.forEach(dates, function(k, v) {
    // Returns each event

    _.forEach(k, function(k2, v2) {
      // Returns multiple objects for each event

      var availableTimes = k2.startTime + " (" + k2.open + " spots left!)",
          timeId = k2.id;
      $('.timeslot select').append('<option data-id="' + timeId +'">' + availableTimes + '</option>');
    });
  });
}

In this case, if you switched appendTimes to only accept selector and have it return a function, the returned function will get called when data is available.

function appendTimes(selector) {
  console.log(selector);
  return function (datas) {
    _.forEach(dates, function(k, v) {
      // Returns each event

      _.forEach(k, function(k2, v2) {
        // Returns multiple objects for each event

        var availableTimes = k2.startTime + " (" + k2.open + " spots left!)",
            timeId = k2.id;
        $('.timeslot select').append('<option data-id="' + timeId +'">' + availableTimes + '</option>');
      });
    });
  }
}

You are calling the method, not assigning a reference to it

}).then(appendTimes(eventDate));

needs to use a closure or binding

}).then(function() { appendTimes(eventDate) });

also you can not return from a promise so the return data is useless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM