简体   繁体   中英

JSON.parse Syntax Error with Button addEventListener

When I run this code, I get an error:

Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () at HTMLButtonElement.button.addEventListener (app.js:20)

app.js:6 is the line that reads "let userInfo = JSON.parse(jsonUser.responseText);

Why is the jsonUser variable not being pushed into the userInfo variable? When I run the code line-by-line in the console it works, but when I assign it to the button click it returns that error.

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>

You are attempting to parse before it's downloaded. Use the callback to wait until it's downloaded and then grab the data you need.

 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> 

The code doesn't wait for .getJSON to complete before moving on. So you need a callback function to use AFTER the data has been obtained from the URL. Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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