ajax 调用中的作用域变量

Ste*_*one 3 javascript ajax

为什么最终的控制台日志是未定义的?变量时间具有全局范围,并且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);  
Run Code Online (Sandbox Code Playgroud)

Eri*_*ger 5

更改async为布尔值 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);
Run Code Online (Sandbox Code Playgroud)

另外,请注意,如果您需要dataType: 'jsonp'在此处使用跨域,您将无法同步——因此请使用 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);    
});
Run Code Online (Sandbox Code Playgroud)

请参阅此处使用 Q.js 的示例:

演示版