gpt4 book ai didi

javascript - 我设置ajax异步: false but not working

转载 作者:行者123 更新时间:2023-11-28 01:34:01 24 4
gpt4 key购买 nike

我正在尝试从其他域获取json,我的代码如下:

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

这个结果应该按照我从数组 url 给出的键的顺序显示。例如:urls = [1,2,3,4]→应该得到[一,二,三,四]但我总是得到错误的顺序!(例如:[二,一,三,四]或[三,四,二,一])发生了什么?“async: false”不起作用吗?为什么?

最佳答案

您使用的 jsonp 请求不支持 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.

所以尝试一下

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

关于javascript - 我设置ajax异步: false but not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21749552/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com