我下面有这段代码,它应该返回调用的结果。我需要同步执行此操作,以便我知道一切都很好,但它似乎不起作用。我做错了什么?
/* jQuery library:
* http://code.jquery.com/jquery-1.9.1.min.js
*/
function getJSON(url){
var result;
$.getJSON(url, { async: false, success: function(data) {
result = data;
alert(data); // **Edit**: also undefined
}});
alert(result); // undefined
return result;
}
最佳答案
getJSON does not honor async:false
getJSON
没有没有async: false
选项。你必须使用 ajax
为此。
根据文档,getJSON
相当于:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
...您可以轻松地添加一个 async: false
选项(目前,请注意 jQuery 将放弃对此的支持)。
I need to do this synchronously so that I know everything is good
您不需要同步执行任何操作来“知道一切都很好”,异步处理结果(无论是“好”还是错误)是完全有可能(并且正常)的。
<小时/>在对您的问题的评论中,您写道:
jsonp? This is the code I am using.
JSON-P与 JSON 不同(并且 getJSON
不会执行 JSON-P,除非 URL 中有 callback=?
或类似内容),并且 JSON-P 本质上异步。与通过 XMLHttpRequest
进行真正的 ajax 调用不同,不可能使 JSON-P 同步。
关于jquery - getJSON 不支持异步 :false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15282821/