我设置AJAX异步:假的,但不工作但不、工作、AJAX

2023-09-10 20:35:48 作者:深柒

我试图让JSON形成其他领域,我的code是如下:

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

这个结果应该显示为秩序的关键,我从阵列的网址给了。 例如:网址= [1,2,3,4]→应该得到[一,二,三,四] 但我总是得到错误的顺序(例如:二,一,三,四]或[三,四,二,一])! 发生了什么? 那是异步:假没有工作?为什么?

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?

推荐答案

您使用的是 JSONP 的要求,不支持异步:假

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

在默认情况下,所有的请求都异步发送(即此设置为   默认值是true)。如果您需要同步请求,设置这个选项   假。跨域请求和数据类型:JSONP请求不   支持同步操作。请注意,同步请求可能   暂时锁定浏览器,禁用而请求的任何行动   是活性

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.

因此​​,尝试

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