ajax调用中的作用域变量

Scope variable in ajax call

本文关键字:作用域 变量 调用 ajax      更新时间:2023-09-26

为什么最终控制台日志未定义?可变时间具有全局作用域,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);  

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'进行跨域,则无法进行同步,因此请使用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);    
});

在这里使用Q.js:看到这样的例子

DEMO

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

确保这两个变量都在全局使用的范围内。这可能奏效。祝你好运

好的,有点做作,但我希望它能说明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