Waiting for AJAX call before code runs using jQuer

2019-08-29 13:24发布

I'm pulling in some JSON and I need that information before the rest of my code runs. I'm very new to jQuery so have been looking at $.when() and setting the AJAX async to be false (which is probably not the best option). I'm also having a problem where my variables are undefined outside of my AJAX call. Here is my code - any help/suggestions would be really appreciated.

//Display nothing while AJAX Call is being made (will add a loading spinner in here)

$('body').css('display','none');

//Ajax call to load images

var test = $.ajax({
  dataType: "json",
  url: "../quiz/scripts/test.json",
  success: function() {
    console.log("Loaded in AJAX");
  var results = test.responseJSON.Items.Pics;
  console.log(results);
  $('body').css('display','block');
}
});

// Trying to retrieve my results variable

console.log("Loaded Outside of AJAX");
console.log(results);

Console is giving me this:

    Loaded Outside of AJAX [VM] quiz.js (23396):18

    Uncaught ReferenceError: results is not defined [VM] quiz.js (23396):19

    XHR finished loading: "http://localhost:8888/.....etc"

    Loaded in AJAX [VM] quiz.js (23396):9

    [Object, Object, Object, Object, Object]

How can I get the text "Loaded in AJAX" to appear before "Loaded Outside of AJAX" and how can I use the variable "results" outside of the AJAX call?

1条回答
相关推荐>>
2楼-- · 2019-08-29 13:42

Try this:

$.getJSON("../quiz/scripts/test.json", null, function(data) { 
    //If you want to, you can call the data here.
}).done(function(data) {
  console.log("The AJAX call is finished! Whoop dee doo!");
  console.log(data);
}); 

If you want to, you can fid some good reference on how a JSON request gets formed in here. I've learned a good bit directly from the API documentation.

查看更多
登录 后发表回答