我得到了一个Jquery调用,它从我得到的php文件中获得一个json响应,json响应很棒,我可以正确地记录响应,但是我似乎无法保存ajax结果之外的信息,它不会更新数组。代码看起来是这样的,我在下面发布了结果。
window.array={name: 'john',color:'red'};
console.log(array['name']);
console.log(array['color']);
$.ajax({
url : 'getJsons.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (data) {
array['name'] = data['name'];
array['color'] = data['color'];
console.log(array['name']);
console.log(array['color']);
}
});
console.log(array['name']);
console.log(array['color']);这将导致以下控制台:
john
red
john
red
marry
blue因此,我第一次正确地获得了控制台,但是它似乎在ajax调用之前加载了脚本,为什么呢?因为这使得我不可能在其余的代码中使用ajax结果,因为它是在脚本加载之后获取的。是否有办法使ajax在其余部分之前运行?
发布于 2013-09-17 13:50:49
由于您不可能知道来自服务器的ajax响应何时到达,因此AJAX默认是异步的。这意味着$.ajax被触发,然后javascript引擎继续执行剩下的代码(在您的示例中,两个console.log在ajax调用之外)。在将来的某个地方,ajax调用可能(也可能不会)从服务器获得响应(并通过更改状态通知这一点)。此时,javascript引擎将处理所谓的“回调”函数代码,这些代码将在ajax调用完成时执行。将回调函数定义为ajax方法的success参数。
这就是为什么执行代码的正确方法是运行一切,这取决于回调函数的结果。将所有内容直接放在其中,或者声明一个独立的函数,然后在成功函数中调用该函数:
$.ajax({
/*...*/,
success : function (data) {
array['name'] = data['name'];
array['color'] = data['color'];
/* either put all your dependent code here */
/* or just call a callback function: */
callback(data);
}
});
/* code to be executed after the ajax call */
function callback(data){
// work with the response here
console.log(data);
}前面的坏主意:
或者,您可以告诉调用是同步的(这是不好的,因为您的浏览器基本上是冻结的,而它等待来自服务器的答案),并保持您的代码原样。
$.ajax({
/*...*/,
async : false,
});
// risk some waiting time (possibly the full duration of a timeout!!)
// the browser is locked during this time
// continue normally
console.log(array['name']);
console.log(array['color']);https://stackoverflow.com/questions/18851619
复制相似问题