在不使用async的情况下将ajax响应分配给全局变量:false [英] Assigning ajax response to global variable without using async: false

查看:160
本文介绍了在不使用async的情况下将ajax响应分配给全局变量: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆