Ajax synchronous callbacks

六眼飞鱼酱① 提交于 2019-12-21 05:56:22

问题


I have a pageTest.html in local folder,this page call a service.ashx?i=...(that return value param passed incremented +1) with follow Ajax code:

.
.
getIncr: function(parameters, success){
       $.ajax({
               async: false, 
               type: methodType,
               url: getTarget,
               data: "n="+parameters,
               dataType:"jsonp",
               success: success
             });
    }
.
.

The html page call this function for m time (with script..):

  .    
  var start = function(){
  .
  .
  var val = 0;
  .      
  .
  for(i=0; i<m; i++)
  {
      Foo.getIncr(val, function(returned_n){
          val = returned_n;
      });

  }

};

During the page loading, the calls are execute in "Asynchronous mode" but i setting "async: false" in Ajax. I read about this problem and found the reason, that is Ajax can't synch call from page.html to service.ashx if there are in different domain. Is there a solution for execute Synch call in page.html to that service.ashx (in different domain)?


回答1:


Well, the problem is that you cannot make synchronous JSONP requests. The way it is implemented is, as Andy pointed out, through a so-called "script tag hack". There is no way jQuery can stop the execution of the javascript application while waiting for a script tag to be filled.

So you are calling the right method of jQuery to make a JSONP request but because it is JSONP, the asynchronous option is not applied and there is no way around it. You have to handle the request asynchronously.

On a side note, it is not a good idea to use $.ajax in synchronous mode anyway. If the request takes too much time to be completed, the browser will stall and chances are your user will get a popup saying the page is not responding.




回答2:


You can't use XMLHttpRequest cross domain at all. It doesn't matter whether it is synchronous or asynchronous.

Since you appear to be using JSON (and jsonp), you should be able to achieve what you want by way of the script tag hack. I believe jQuery has this built in to it (is it jQuery you're using by the way?):

http://docs.jquery.com/Release:jQuery_1.2/Ajax#Cross-Domain_getJSON_.28using_JSONP.29



来源:https://stackoverflow.com/questions/631609/ajax-synchronous-callbacks

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