带有异步错误的 jQuery ajax 调用不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12930202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery ajax call with async false is not working
提问by Maulik Vora
Here I have pasted my code, I want to return the response of $.ajax as response of function a(). But before the result comes up of ajax call, it is returning the empty f. please help on this
这里我粘贴了我的代码,我想返回 $.ajax 的响应作为函数 a() 的响应。但是在 ajax 调用的结果出现之前,它返回的是空的 f。请帮忙解决这个问题
a = function()
{
var f = '';
$.ajax({
url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=immaulikvora&count=1&page=1&include_entities=1&callback=?',
dataType: 'json',
async: false,
success: function(data) {
f = data;
}
});
return f;
};
var lid = a();
alert(lid);
回答by Murali Murugesan
Please assign the ajax to jqXHR object and reading the responseText will help you.
请将 ajax 分配给 jqXHR 对象,阅读 responseText 会对您有所帮助。
var jqXHR=$.ajax({
url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=immaulikvora&count=1&page=1&include_entities=1&callback=?',
dataType: 'json',
async: false
});
jqXHR.responseText // This will give you the result
回答by Neverever
I guess you are using jQuery 1.8+
我猜你正在使用 jQuery 1.8+
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.ajax/
Please read the fine print.
请阅读细则。
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated;
you must use the complete/success/error callbacks.
从 jQuery 1.8 开始,不推荐使用带有 jqXHR ($.Deferred) 的 async: false ;
您必须使用完整/成功/错误回调。
try
尝试
回答by b_levitt
Unless you work for twitter, I would assume it is failing because "Cross-domain requestsand dataType: "jsonp" requests do not support synchronous operation."
除非你为 twitter 工作,否则我会认为它失败了,因为“跨域请求和数据类型:“jsonp”请求不支持同步操作。”
Deprecated != removed and even if it did I take the deprecation is in the context of the returned jqXHR which are not being used here.
已弃用 != 已删除,即使我确实弃用了,也是在此处未使用的返回 jqXHR 的上下文中。
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.ajax/
It looks like @Murali provides a work-around, but the above is important to point out for those having issue with same-domain requests.
看起来@Murali 提供了一种解决方法,但是对于那些遇到同域请求问题的人来说,上面的内容很重要。