问题
I have gone through many posts. Some say that after jquery 1.8, its deprecated. For some, it still works. How can I implement this
$.ajaxSetup({async:false});
duration_reco = $.ajax({
url : newurl,
async : false,
dataType : 'json',
});
console.log(duration_reco.responseText);
It says durtaion_reco is undefined. I have checkeed to see that duration_reco cotaines valid data. the ajax request is executing synchronously.
回答1:
$.ajax
supports many different types of requests (which jQuery calls transports), and hides them from the user (normal XHR, XHR with CORS, JSONP). This is good as it means you can fire any URL at $.ajax()
, and not have to worry about what is happening behind the scenes.
However, it is bad in that not all types of requests support all of the options $.ajax()
supports. Things start to fail, seemingly randomly, when this happens. This is what is happening here.
Since you're requesting an resource from another domain, $.ajax()
is making a JSONP request. To understand how JSONP works, see Can anyone explain what JSONP is, in layman terms?.
Basically, JSONP requests cannot happen synchronously. You can only perform them asynchronously, which involves altering your code to;
duration_reco = $.ajax({
url : newurl,
dataType : 'json'
}).done(function (obj) {
console.log(obj);
});
Synchronous AJAX requests are bad anyway. They lock up the browser. There is hardly ever a reason to use them. Avoid them at all costs. I cannot emphasise this enough.
You should also make sure your newurl
variable starts with either http://
or https://
; otherwise it'll be treated as a path on your current domain, and http://www.yourdomain.com/gdata.youtube.com/feeds/api...
will be requested.
来源:https://stackoverflow.com/questions/22270902/ajax-synchronous-requests