在不使用async的情况下将ajax响应分配给全局变量:false [英] Assigning ajax response to global variable without using async: false
问题描述
我有以下脚本:
var myData;
$.ajax({
url: "/foo.php",
dataType : 'json',
type: "POST",
async: false
})
.done(function( data ) {
myData = data;
});
我要做的就是将来自ajax响应的数据分配给myData
,并在我的脚本中进一步引用此变量.上面的代码似乎可以工作,但是依赖于我所读过的async: false
并不是一件好事.如果我将其注释掉(因此使用默认的async: true
),则不会为myData
分配任何内容.
All I want to do is assign the data from the ajax response to myData
and refer to this variable further down in my script. The above code seems to work but relies on async: false
which I've read is not a good thing. If I comment this out (and therefore it uses the default async: true
) nothing is assigned to myData
.
我已阅读以下帖子 jQuery ajax成功回调函数定义但是无法适应,因此我可以访问myData
中的数据.我还注意到,有人在2013年问过这个问题,所以不确定它是否仍然正确或正确的解决方法?
I've read the following post jQuery ajax success callback function definition but can't adapt that so I can access the data in myData
. I also note that question was asked in 2013 so not sure if it's still accurate or the right way to go about this?
这应该怎么做?我正在使用jquery v1.11.1
How is this supposed to be done? I'm using jquery v1.11.1
推荐答案
好,因此以下方法似乎可行.我已经删除了async: false
并添加了一个函数,用于引用ajax调用中的数据.
Ok so the following seems to work. I've removed async: false
and added a function where I'm referring to the data from the ajax call.
$.ajax({
url: "/foo.php",
dataType : 'json',
type: "POST"
})
.done(function( data ) {
buildTree(data);
});
function buildTree(data) {
console.log(data);
// other code that needs 'data'
}
根据@pwolaq的建议,我认为这是正确的.
I assume this is correct based on what @pwolaq suggested.
这篇关于在不使用async的情况下将ajax响应分配给全局变量:false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!