異步獲取后,我在 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
});
uj5u.com熱心網友回復:
您的代碼應該如下所示,您使用了 async-await 并使用了回呼,并且您在資料不可用時列印了資料。
async function listFiles(dir) {
try {
const response = await fetch('action.php', {
method: 'POST',
mode: "same-origin",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ dir: dir })
})
const json_data = await response.json();
console.log('Success:', json_data);
return json_data;
}
catch (error) {
console.error('Error:', error);
}
}
async function printJsonData() {
var json = await listFiles('images');
$.each(json, function (index, val) { // now it should work :)
console.log("index: " index "; value: " val);
})
console.log(json); //this shows fetched json object's content
}
printJsonData();
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362571.html
標籤:javascript 查询 json 异步 每个
下一篇:參考時執行的js異步函式
