等待AJAX调用code运行使用jQuery之前 [英] Waiting for AJAX call before code runs using jQuery
问题描述
我拉一些JSON,我需要我的code运行的其余部分之前的信息。我很新jQuery的),所以一直在寻找$。当(并设置AJAX异步是假的(这可能不是最好的选择)。我也有我的地方变量的不确定我的AJAX调用之外的问题。这里是我的code - 任何帮助/建议将是非常美联社preciated
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.
//显示什么,而正在取得AJAX调用(将在这里添加加载微调)
//Display nothing while AJAX Call is being made (will add a loading spinner in here)
$('body').css('display','none');
// Ajax调用加载图像
//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]
我怎样才能得到文本装在AJAX装AJAX外之前出现,我如何使用变量结果的AJAX外面打电话?
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?
推荐答案
试试这个:
$.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);
});
如果你愿意,你可以在FID一个JSON请求被如何形成的这里一些很好的参考。我从API文档学到了好位直接。
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.
这篇关于等待AJAX调用code运行使用jQuery之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!