javascript - 使用 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 实际上是在一个对象内部,而我没有以正确的方式访问它......
解决方案
这是使宪章工作的代码仍然存在,但没有阻塞。我运行了许多故障测试,它发生在请求上下文之外,或者是对字符串的解析运行两次的双重打击。下面示例中的脚本文件只有以下代码。没有半冒号没有别的。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>
推荐阅读
- reactjs - 如果已经是全局包,如何将模块添加到 package.json?
- javascript - 如何在 HTML 页面的按钮单击上运行 python 脚本或批处理文件
- node.js - 节点不会更改为最新版本 (14.4.0)
- c# - 不断收到“System.Security.Claims.ClaimsIdentity”标记为 IsAuthenticated = true 错误 c# .NET Core
- rotation - 轮换的证书能否解密在轮换之前加密的值?
- java - 无法将图像上传到 Firebase
- vis.js - visjs 物理 - 删除节点时保留节点
- python - 从数据框列表创建单个熊猫数据框
- reactjs - 如何使用fabric react nav组件添加自定义html属性?
- java - 执行 .sh 文件以运行我的 java 项目时遇到错误