【发布时间】:2021-12-31 09:11:34
【问题描述】:
异步获取后在 jQuery 中迭代 json 对象时遇到问题。 使用异步函数“listFiles”,我成功地获得了所需的目录(dir)文件列表,至少 console.log 显示了带有内容的 json。 但是当我尝试在获取的文件列表 json 对象上调用 $.each 时,$.each 根本不起作用。 $.each 函数中的 console.log 应该会输出一些东西。
async function listFiles(dir){
var json_data = await fetch('action.php', {
method: 'POST',
mode: "same-origin",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({dir:dir})
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
return data
})
.catch((error) => {
console.error('Error:', error);
});
return json_data;
}
var json = listFiles('images');
$(() => {
$.each(json, function(index,val){ //this function doesn't work, dunno why :(
console.log("index: "+index+"; value: "+val);
})
console.log(json); //this shows fetched json object's content
});
【问题讨论】:
-
你读过链接的副本吗?您需要
await返回listFiles或将您的迭代回调放在then语句中。一旦进入异步区域,始终处于异步区域。
标签: javascript jquery json asynchronous each