ajax调用中的范围变量

时间:2013-08-09 14:58:37

标签: 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);  

3 个答案:

答案 0 :(得分:4)

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);

另请注意,如果您需要在此处使用dataType: 'jsonp'进行跨域,则无法进行同步 - 因此请使用承诺。

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);    
});

使用Q.js查看这样的示例:

<强> DEMO

答案 1 :(得分:0)

在您的代码中,您将全局变量'time'初始化为'data'。这个数据变量来自哪里?如果数据变量也不是全局的,当您尝试使用console.log(time);时,它可能是未定义的,因为数据变量未定义。

确保两个变量都在全局范围内使用。那可能有用。祝好运!

答案 2 :(得分:0)

好的,有点做作,但我希望它能说明time的范围和时间......

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

window.setTimeout("console.log('time: '+time)",3000);

JSfiddle

相关问题