在Ajax调用范围变 [英] Scope variable in ajax call
本文介绍了在Ajax调用范围变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么最终的控制台日志是不确定的?变量时有一个全球范围和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(时间);
另外,注意,如果你需要使用数据类型: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:
这篇关于在Ajax调用范围变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文