storing AJAX response into variable for use later in script?

二次信任 提交于 2020-01-11 14:39:16

问题


here is the gist of my code: https://gist.github.com/tconroy/e52e0e7402face8f048e

Basically, my program is broken down into several steps:

  1. retrieve user input from N number of inputs (user can add/remove)
  2. perform AJAX query on each input, retrieving JSON formatted weather data for each.
  3. on successful AJAX, pass the data to dataReady() function.
  4. dataReady() function stores the data into a global Array[]

The problem is the AJAX data is not storing in the global array. how can I save the JSON response for use later in the program? I need to store all my weather data in one array, so I can iterate through it to create my graph later in the program.

The part causing issues in particular:

function getWeatherData(){
  // set up query strings.
  var queryBase  = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=",
      queryEnd   = "&format=json&num_of_days=5&key="+weatherAPIKey;

  // iterate through each address input
  $('.inp').each(function(){
    // setup query
    var inp   = this;
    var addr  = encodeURIComponent( inp.value );
    var query = queryBase + addr + queryEnd;
    // perform query
    $.ajax({
      url: query,
      async: false,
      dataType: 'jsonp',
      success: function(json){
        // format our response data into object, push it into container array.
        var objName = String(decodeURIComponent(addr));
        var objVals = json.data.weather;
        dataReady(objName, objVals);
      },
      error: function(){
        alert(errMsg);
      }
    });
  }); // end $('.inp').each();
  // setup the graph
  setupGraph();
} // end getWeatherData();


function dataReady(objName, objVals) {
  console.log('dataReady() called.');
  responseValues[objName] = objVals;
}

回答1:


From what I understand (see comments) you are dealing with a typical problem with asynchronous calls. You call AJAX, then you call setupGraph() but the ajax response will arrive after that call, because it is asynchronous.

First of all, doing async: false is bad, wrong and the source of all evil. Don't use it never ever. In your case it won't even work, because you can't force JSONP to be synchronous. But even if you could let me repeat my self, because this is important: don't ever use async: false.

Now back to your problem. What you should is to use deferred callbacks instead:

var reqs = [];
$('.inp').each(function(){
    // some code
    reqs.push(
        $.ajax({
            // some settings
        })
    );
});

$.when.apply($, reqs).then(function() {
    setupGraph();
});

Read more about $.when here: https://api.jquery.com/jQuery.when/



来源:https://stackoverflow.com/questions/23525414/storing-ajax-response-into-variable-for-use-later-in-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!