<分区>
我正在设置一个小网站,除其他外(对于这个问题很重要)将您当前的位置数据保存在一个 var 中,它从 ipinfo API ( https://ipinfo.io/json ) 检索
我尝试使用 JSON.parse() 解决了我的网站在通常显示位置的 p-tag 处显示“未定义”的问题,然后在半秒后将我重定向到 url/[object%20Object]。通过解析,我得到以下错误 console.log:(请参阅下文)
JSON 响应可以在不保存的情况下使用而不会导致任何问题。要查看它的外观,请单击上面的 API 链接。
这是我的 JS 代码:
var location;
// called when the document is fully loaded
$(document).ready(function(){
// gets your current location data and displays it
$.get("https://ipinfo.io/json", function(response) {
location = JSON.parse(response);
console.log(location);
document.querySelector('.location').innerHTML = location.city;
});
这是 HTML:
<h4>You are playing from:</h4>
<div>
<p class="location"></p>
<p class="country"></p>
<p class="region"></p>
</div>
<div class="row">
<div class="column">
<h3>Column 1</h3>
<p id="city_a">
</p>
</div>
<div class="column">
<h3>Column 2</h3>
<p id="city_b">
</p>
</div>
这是我得到的控制台错误:
VM102:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
at Object.success ((index):64)
at u (VM94 jquery-3.3.1.min.js:2)
at Object.fireWith [as resolveWith] (VM94 jquery-3.3.1.min.js:2)
at k (VM94 jquery-3.3.1.min.js:2)
at XMLHttpRequest. (VM94 jquery-3.3.1.min.js:2)
任何事情都会有所帮助 :) 提前致谢!