I set ajax async: false but not working

时间秒杀一切 提交于 2019-12-24 11:35:35

问题


I'm trying to get json form other domain, my code is as below:

var token = '';
function getData(){
  console.log("get data suc");
  for (var i=0; i < urls.length; i++){
     var code = 'http://example.com/api/'+ urls[i];
     $.ajax({
       async: false,
       url: code,
       type: 'GET',
       dataType: 'jsonp',
       success: function(data) { showData(data); },
       error: function() { console.log('ajax Failed!'); },
       beforeSend: setHeader,
     });
  }
}
function showData(data){
  $("<tr></tr>").append("<td>" + data + "</td>")
    .appendTo("#results");
  console.log(data);
}
function setHeader(xhr) {
  xhr.setRequestHeader('Authorization', token);
}

This result should be display as order the key I gave from array urls. ex: urls = [1,2,3,4]→should get [one,two,three,four] but I always get the wrong order!(ex: [two,one,three,four] or [three,four,two,one]) What happened? Is that "async: false" didn't work? And why?


回答1:


You are using a jsonp request which does not support async:false.

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

So try

function getData() {
    function request(urls, i) {
        var code = 'http://example.com/api/' + urls[i];
        $.ajax({
            async: false,
            url: code,
            type: 'GET',
            dataType: 'jsonp',
            success: function (data) {
                showData(data);
            },
            error: function () {
                console.log('ajax Failed!');
            },
            beforeSend: setHeader,
        }).always(function () {
            i++;
            if (i < urls.length) {
                request(urls, i);
            }
        });
    }
    console.log("get data suc");
    request(urls, 0);
}



回答2:


Your assumption is correct, async: false does not work for JSONP requests.

If you really need synchronous behavior, you'd need a sequence of requests where the success callback from the first initiates the second, and so on. Really, though, it would be preferable if you simply handled the responses in the order that they appear.

For instance, you could pass the index variable:

function getCallback(i) {
   return function(data) {
      showData(data, i);
   };
};

...

$.ajax({
   ...
   success: getCallback(i)
 });

...

function showData(data, i){
   // use 'i' here to determine where to insert the record
}


来源:https://stackoverflow.com/questions/21749552/i-set-ajax-async-false-but-not-working

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