本文介绍了我设置AJAX异步:假的,但不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让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请求不 支持同步操作。请注意,同步请求可能 暂时锁定浏览器,禁用而请求的任何行动 是活性
因此,尝试
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);
}
这篇关于我设置AJAX异步:假的,但不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!