按钮addEventListener的JSON.parse语法错误

时间:2017-05-10 22:21:16

标签: javascript jquery html json

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

  

Uncaught SyntaxError:位于0的JSON中的意外标记u       在JSON.parse()       在HTMLButtonElement.button.addEventListener(app.js:20)

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>

3 个答案:

答案 0 :(得分:0)

您正在尝试在下载之前进行解析。使用回调等待它下载,然后获取所需的数据。

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>

答案 1 :(得分:0)

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

var jsonUser;
$.getJSON('https://ipinfo.io/json', function(data){
    jsonUser=data;
    console.log(jsonUser);
    ...
});

答案 2 :(得分:0)

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;
  });
});