I set ajax async: false but not working

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?

Answers:

Answer

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

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
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.