首页 > 解决方案 > 使用 JSON 从给定的外部 json 对象中使用 async/await 方法填充选择下拉列表,并在 vanilla js 中尝试和捕获语句

问题描述

我正在执行一个测试,我必须在其中填充一个表单并从驻留在外部文件中的给定对象中获取选项数据。我们的想法是获取此数据以填充两个下拉选择列表,一个用于 chosen 州,另一个用于其相应的城市,实现此目的的方法应该是使用 async / await 方法并尝试和捕获语句。这是 json 文件 data.js:

var stateLocs = {
    "Alabama":["Birmingham","Huntsvillen"],
    "California":["Los Angeles","San Diego"],
    "Georgia":["Atlanta", "Augusta"],
    "New York":["New York City","Buffalo","Rochester"]
};

这就是我到目前为止所做的,因为它检索到我一个错误:

    const getDataAsync = async () => {
  try {
    const res = await fetch("/js/data.js")
    const data = await JSON.parse()

    console.log(data.results)
    data.results.map(stateLocs => console.log(stateLocs))
  } catch (err) {
    const errorObject = JSON.parse(err);
    console.log(errorObject);
  }
};
getDataAsync();

这是检索到的错误:

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

    getDataAsync http://localhost:3000/js/scrypts.js:9
    async* http://localhost:3000/js/scrypts.js:13
scrypts.js:9:30
    getDataAsync http://localhost:3000/js/scrypts.js:10
    AsyncFunctionNext self-hosted:690
    (Asíncrono: async)
    <anonymous> http://localhost:3000/js/scrypts.js:13

我相信这是因为 json 实际上是在一个对象内部,而我没有以正确的方式访问它......

标签: javascriptjsonobjectasynchronousasync-await

解决方案


这是使宪章工作的代码仍然存在,但没有阻塞。我运行了许多故障测试,它发生在请求上下文之外,或者是对字符串的解析运行两次的双重打击。下面示例中的脚本文件只有以下代码。没有半冒号没有别的。fetch 和 ajax 将在收到后自动解析它们,如下例所示。

{
    "Alabama": ["Birmingham", "Huntsvillen"],
    "California": ["Los Angeles", "San Diego"],
    "Georgia": ["Atlanta", "Augusta"],
    "New York": ["New York City", "Buffalo", "Rochester"]
}



    <!doctype html>

<html>
  <head>


  </head>

  <body>
    <h1>Hello Plunker!</h1>
  </body>
  <script>
async function getData () {
await fetch('./lib/script.js')
  .then((response) => {
    return response.json()
  })
  .then((data) => {
    console.log('fetch finished');
  console.log(data);

  })

};


function getData2(){
let xhr = new XMLHttpRequest();
xhr.open('GET', './lib/script.js');

xhr.responseType = 'json';

xhr.send();

xhr.onload = function() {
  console.log('ajax finished');
 console.log(xhr.response);  
};

};
getData();
getData2();
  </script>
</html>

结果 在此处输入图像描述 只需在最后一个 then 或 onload 函数而不是 console.log 中运行您的下拉逻辑,如上例所示。


推荐阅读