I have an issue with iterating json object in jQuery after fetching asynchronly. With async function 'listFiles' I managed to succesfully get the desired filelist of directory (dir), at least console.log shows json with content. But when I try to call $.each on fetched filelist json object, $.each simply doesn't work. The console.log inside $.each function should output something.
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
});
CodePudding user response:
You code should look something like below, you were using async-await and also using callbacks, and also you were printing data when it was not available.
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();
CodePudding user response:
You can use for...in
, Object.keys
or Object.ertries
to iterate object
for (const [key, value] of Object.entries(json)) {
console.log(`${key}: ${value}`);
}
// or
$.each(Object.keys(json), function(index,val){
console.log("index: " index "; value: " json[val]);
})
Object.keys(json).forEach(key => console.log(json[key]);
// or
for (let key in json) console.log(json[key]);