Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

javascript - storing AJAX response into variable for use later in script?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...