gpt4 book ai didi

javascript - AJAX 调用和异步

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

我正在调用两个网址来获取数据并将其放在表格中。问题是,当只有一个 ajax 调用时,所有内容都会按预期顺序加载。当有两个时,一切都会崩溃。我从 promise 开始,但被告知这不是一个好主意[编辑1]我实现它的方式。请提出建议?

代码示例:

 $.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 的每个属性(域、DNS、电子邮件 Web)的两列。

html 表格:

<div class= "container_1">

<table class="table" border="1">
<th class="panel-heading"> </th>
<tr class="domain"> </tr>
<tr class="table-group1">
</tr>
</table>

最佳答案

这是处理 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
});

由于您现在手头有所有数据,您应该能够根据需要格式化输出

关于javascript - AJAX 调用和异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35053198/

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