我有几个 ajax 将其结果附加到 HTML 表中。 代码示例是这样的
$.ajax({
url: '<?php echo Url::toRoute('booking/get_1_rate'); ?>',
type: 'GET',
dataType: 'json',
async: true,
data:{
},
success: function(data){
display_rate(data);
}
});
$.ajax({
url: '<?php echo Url::toRoute('booking/get_2_rate'); ?>',
type: 'GET',
dataType: 'json',
async: true,
data:{
},
success: function(data){
display_rate(data);
}
});
function display_rate(data)
{
$.each(data.departure, function(index, value)
{
html_depart = "<tr><td>value.airline_code</td></tr>";
$('#table_body_search_flights_depart').append(html_depart);
});
}
问题是HTML表格中出现的结果取决于哪个ajax先完成,那么晚的ajax结果将不会出现在HTML表格中。 看起来 jquery .append() 只是追加第一个 ajax 结果。
我检查了第二个ajax中包含html的字符串及其良好/成功,但该字符串没有附加到第二个ajax中的html。仅第一个ajax中附加到html的字符串
有什么想法吗?
最佳答案
您可以看看我在这里找到的一些方便的方法: https://medium.com/coding-design/writing-better-ajax-8ee4a7fb95f
它将允许您进行多个 ajax 调用并以几种不同的方式使用适当的 promise 。
似乎对您的情况特别有用的方法可能是 .done() 和/或 .when() --
多个 AJAX 调用
var a1 = $.ajax({...}),
a2 = $.ajax({...});
$.when(a1, a2).done(function(r1, r2) {
// Each returned resolve has the following structure:
// [data, textStatus, jqXHR]
// e.g. To access returned data, access the array at index 0
console.log(r1[0]);
console.log(r2[0]);
});
AJAX 调用的依赖链
var a1 = $.ajax({
url: '/path/to/file',
dataType: 'json'
}),
a2 = a1.then(function(data) {
// .then() returns a new promise
return $.ajax({
url: '/path/to/another/file',
dataType: 'json',
data: data.sessionID
});
});
a2.done(function(data) {
console.log(data);
});
我从链接中获取了这两个示例。
希望有帮助!
关于javascript - 带有 jquery .append 的多个异步 AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48782141/