【发布时间】:2020-07-20 16:56:19
【问题描述】:
我有以下 HTML 结构,我想用 Ajax 调用填充每个块,但是当我使用 async:false 时,它在 Jquery 3x 中不起作用
<ul class="tray" id="hiphop"></ul>
<ul class="tray" id="rnb"></ul>
<ul class="tray" id="afro"></ul>
<ul class="tray" id="blues"></ul>
<ul class="tray" id="dancehall"></ul>
<ul class="tray" id="rumba"></ul>
<ul class="tray" id="samba"></ul>
<ul class="tray" id="trap"></ul>
<ul class="tray" id="rap"></ul>
我想要执行的是:
- 浏览 HTML 结构并检索所有 ID
- 为每个 ID 向我的服务器文件发送请求并
- 根据每个block的ID显示得到的结果
这是我最初的 JS 代码:
$('.tray').each(function(){
$id = $(this).attr('id');
$.ajax({
type: 'GET',
url: 'feed',
data: 'c='+$id,
cache: false,
// async: false,
success:function(datas){
$('#'+$id+'').html(datas);=
},
error:function (){
console.log('error ...');
}
});
});
但是在阅读了一个叫做 Promise 的东西之后,我尝试了这个,但老实说,我什至不明白我在做什么
var $array = $.map($('ul.tray'), function(value, index) {
return [value];
});
var promises = [];
$array.forEach(function(item) {
// you can access item.id and item.title here
$id = $(this).attr('id');
promises.push(
$.ajax({
type: 'GET',
url: 'feed',
data: 'c='+$id,
cache: false,
})
);
});
Promise.all(promises).then(function(results) {
// all ajax calls done here, results is an array of responses
//console.log($results);
});
你能帮我在不使用异步的情况下用 Ajax 填充那些空块吗? 任何帮助将不胜感激
【问题讨论】:
标签: jquery ajax loops asynchronous