繁体   English   中英

带有按钮addEventListener的JSON.parse语法错误

[英]JSON.parse Syntax Error with Button addEventListener

运行此代码时,出现错误:

未捕获到的SyntaxError:JSON中意外的令牌u在HTMLButtonElement.button.addEventListener(app.js:20)的JSON.parse()位置0

app.js:6是读取“ let 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>

您正在尝试解析,然后再下载。 使用回调函数等待下载完成,然后获取所需的数据。

 const button = document.querySelector("#button"); button.addEventListener('click', () => { let jsonUser = $.getJSON('https://ipinfo.io/json', function(userInfo) { let ip = userInfo.ip; let country = userInfo.country; let region = userInfo.region; let city = userInfo.city; let isp = userInfo.org; let zipcode = userInfo.postal; console.log(ip, country, region, city, isp, zipcode); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <!-- Compressed jQuery Min v3.2.1 - 70 KB --> <title>Test Website</title> </head> <body> <button id="button">Test Complete</button> </body> </html> 

该代码不会继续等待.getJSON完成。 因此,在从URL获得数据之后,您需要一个回调函数来使用。 像这样:

var jsonUser;
$.getJSON('https://ipinfo.io/json', function(data){
    jsonUser=data;
    console.log(jsonUser);
    ...
});
const button = document.querySelector("#button");
button.addEventListener('click', function() {
$.getJSON("https://ipinfo.io/json")
  .done(function( json ) {
    console.log(json);
    let userInfo = json; //JSON.parse(json)
    let ip = userInfo.ip;
    let country = userInfo.country;
    let region = userInfo.region;
    let city = userInfo.city;
    let isp = userInfo.org;
    let zipcode = userInfo.postal;
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM