在Ajax调用范围变范围、Ajax

2023-09-10 13:50:07 作者:热情喂狂风

为什么最终的控制台日志是不确定的?变量时有一个全球范围和Ajax调用是异步。

这是我的code:

  VAR时间;
$阿贾克斯({
    异步:假的,
    键入:GET,
    网址:http://www.timeapi.org/utc/now.json
    成功:功能(数据){
        的console.log(数据);
        时间=数据;
    },
    错误:功能(数据){
      的console.log(KO);
    }
});

执行console.log(时间);
 

解决方案

修改异步的布尔值false。

http://api.jquery.com/jQuery.ajax/

VAR时间; $阿贾克斯({     异步:假的,     键入:GET,     网址:http://www.timeapi.org/utc/now.json     成功:功能(数据){         的console.log(数据);         时间=数据;     },     错误:功能(数据){         的console.log(KO);     } }); 执行console.log(时间); ajax返回data穿多个值,通过ajax返回多个值的代码实例教程

另外,注意,如果你需要使用数据类型:JSONP这里跨域,您将无法同步 - 所以使用一个承诺

  VAR时间;
$阿贾克斯({
    数据类型:JSONP,
    键入:GET,
    网址:http://www.timeapi.org/utc/now.json
    成功:功能(数据){
        时间=数据;
    },
    错误:功能(数据){
        的console.log(KO);
    }
})
。然后(函数(){//使用一个承诺,以确保我们同步关闭JSONP
    执行console.log(时间);
});
 

来看一个示例这里使用Q.js这样的:

演示

Why the final console log is undefined?Variable time has a global scope and ajax call is async.

This is my code:

var time;
$.ajax({
    async: false,
    type: 'GET',
    url: "http://www.timeapi.org/utc/now.json",
    success: function(data) {
        console.log(data);  
        time=data;
    },
    error: function(data) {
      console.log("ko");
    }
});

console.log(time);  

解决方案

Change async to the boolean false.

http://api.jquery.com/jQuery.ajax/

var time;
$.ajax({
    async: false,
    type: 'GET',
    url: "http://www.timeapi.org/utc/now.json",
    success: function (data) {
        console.log(data);
        time = data;
    },
    error: function (data) {
        console.log("ko");
    }
});

console.log(time);

Also, note that if you need to use dataType: 'jsonp' here for cross-domain, you won't be able to synchronize -- so use a promise.

var time;
$.ajax({
    dataType: 'jsonp',
    type: 'GET',
    url: "http://www.timeapi.org/utc/now.json",
    success: function (data) {
        time = data;
    },
    error: function (data) {
        console.log("ko");
    }
})
.then(function(){ // use a promise to make sure we synchronize off the jsonp
    console.log(time);    
});

See an example like this here using Q.js:

DEMO