jQuery ajax call with async false is not working

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

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

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); 

回答1:

I guess you are using jQuery 1.8+

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.

try

http://jsfiddle.net/UgrLE/



回答2:

Please assign the ajax to jqXHR object and reading the responseText will help you.

 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 


回答3:

Unless you work for twitter, I would assume it is failing because "Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation."

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.

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!