我正在使用 jQuery 函数 $.getJSON
从服务器端获取一些数据,代码如下:
function (){
$.getJSON("someURI",function(result){
//this alert works fine
alert(result.msg)
});
// this prints the data as undefined
alert(result.msg);
}
如何更改从$.getJSON
返回的“结果”的范围为了使其全局化..使第二个警报打印其值不是未定义的? ??
最佳答案
你不能。 AJAX 是异步的,这意味着您只能在 success
回调中访问 result
变量。您可以将其设置为全局,但请记住,紧随 $.getJSON
调用之后的行将在 success
回调执行渲染之前很久被调用没用。
因此没有全局变量,在回调中使用 AJAX 调用的结果:
function () {
$.getJSON('someURI', function(result){
// only here you can hope to consume the results of an AJAX call
alert(result.msg)
});
}
这就是 AJAX 的工作原理。 AJAX 中的 A 代表异步。
关于javascript - $.getJSON 使其结果全局化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12020125/