我正在调用两个网址来获取数据并放在桌子上。问题是,当只有一个ajax调用时,所有内容都按照它应该的顺序加载。当有两个人时,所有的地狱都会破裂。我从承诺开始,但被告知这不是一个好主意[edit1]我实施它的方式。建议好吗?
代码示例:
$.ajax({
"url":url1,
"crossDomain":true,
"dataType":"jsonp",
'success': function(response){
var datee = response.results.collection1[0].date;
var collection = response.results.collection2;
$(".table-group1").append('<tr><td class=well">'+ datee.substr(56,60) +'</td></tr>');
for (var i = 1; i < collection.length; i++){
$(".table-group1").append('<tr>' + '<td class="well">' + collection[i].domain.href + '</td>' + '<td class="well">' + collection[i].dns + '</td>' + '<td class="well">' + collection[i].mail + '<td class="well">' + collection[i].web + '</td>' +'</tr>');}},
error: function(err){
alert('error!' + err);
}
});
$.ajax({
"url":url2,
"crossDomain":true,
"dataType":"jsonp",
'success': function(response){
var datee = response.results.collection1[0].date;
var collection = response.results.collection2;
$(".table-group1").append('<tr><td class=well">'+ datee.substr(56,60) +'</td></tr>');
for (var i = 1; i < collection.length; i++){
$(".table-group1").append('<tr>' + '<td class="well">' + collection[i].domain.href + '</td>' + '<td class="well">' + collection[i].dns + '</td>' + '<td class="well">' + collection[i].mail + '<td class="well">' + collection[i].web + '</td>' +'</tr>');
}},
error: function(err){
alert('error!' + err);
}
});
所需的输出是一个表,其中包含来自url1和url2的每个属性(domain,dns,email web)的两列。
html table:
<div class= "container_1">
<table class="table" border="1">
<th class="panel-heading"> </th>
<tr class="domain"> </tr>
<tr class="table-group1">
</tr>
</table>
答案 0 :(得分:2)
以下是你如何处理ajax方
var p1 = $.ajax({
url: url1,
crossDomain: true,
dataType: "jsonp"
});
var p2 = $.ajax({
url: url2,
crossDomain: true,
dataType: "jsonp"
});
Promise.all([p1,p2])
.then(function(results) {
//results[0] is the the same as response in your code for url1
//results[1] is the the same as response in your code for url2
});
由于您现在拥有所有数据,您应该可以根据需要格式化输出
答案 1 :(得分:1)
如果您想对两个ajax调用进行排序,以便在另一个启动之前完成,请执行此操作;
$.ajax(...).then(function() {
return $.ajax(...);
}).then(function(){
// both are done here
});