【问题标题】:How to iterate json object after async fetching json in jQuery?在jQuery中异步获取json后如何迭代json对象?
【发布时间】: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
});

【问题讨论】:

标签: javascript jquery json asynchronous each


【解决方案1】:

您的代码应该如下所示,您正在使用 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();

【讨论】:

  • 哇!!!!这有效! :))) 但是怎么做??
  • 哦,我明白了!我没有将数据与 try 语句中的 await json.response 异步存储在 const 变量中等等。哦,天哪,我现在知道什么。谢啦!! :)
猜你喜欢
  • 2011-06-05
  • 1970-01-01
  • 2021-03-06
  • 2017-05-21
  • 2019-07-21
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
相关资源
最近更新 更多