【发布时间】:2017-05-10 22:21:15
【问题描述】:
当我运行这段代码时,我得到一个错误:
Uncaught SyntaxError: 位置 0 处 JSON 中的意外标记 u 在 JSON.parse() 在 HTMLButtonElement.button.addEventListener (app.js:20)
app.js:6 是“让 userInfo = JSON.parse(jsonUser.responseText);
为什么 jsonUser 变量没有被推入 userInfo 变量?当我在控制台中逐行运行代码时,它可以工作,但是当我将其分配给按钮时,单击它会返回该错误。
JAVASCRIPT:
//Get information about where the data is coming from
const button = document.querySelector("#button");
button.addEventListener('click', () => {
let jsonUser = $.getJSON('https://ipinfo.io/json');
console.log(jsonUser);
let userInfo = JSON.parse(jsonUser.responseText);
let ip = userInfo.ip;
let country = userInfo.country;
let region = userInfo.region;
let city = userInfo.city;
let isp = userInfo.org;
let zipcode = userInfo.postal;
});
HTML:
<html>
<head>
<!--
Compressed jQuery Min v3.2.1 - 70 KB
-->
<title>Test Website</title>
</head>
<body>
<button id="button">Test Complete</button>
<script src="jquery-3.2.1.min.js"></script>
<script src="app.js"></script>
</body>
</html>
【问题讨论】:
-
$.getJSON('https://ipinfo.io/json');是异步的。它返回一个 jqXHR,在未来的某个时候会有一个 responseText 属性。但是,在脚本的下一行,所述属性将不存在。当你逐行运行它时,当你在它之后运行它时,它已经有时间完成并因此具有属性。 -
检查响应负载中的标头 Content-Type。是 application/json 还是别的什么?
标签: javascript jquery html json