[英]How do I get the value of certain objects from this array?
I want to get the value of "city" and "country".我想获得“城市”和“国家”的价值。
Here's my HTML and javascript code.这是我的 HTML 和 javascript 代码。
I've tried:我试过了:
<pre id="json-result"></pre>
<p><span id="city"></span></p>
<p><span id="country"></span></p>
<script>
var result = document.getElementById("json-result");
const Http = new XMLHttpRequest();
window.addEventListener("load", function () {
console.log("getLocation Called");
var bdcApi = "https://api.bigdatacloud.net/data/reverse-geocode-client"
navigator.geolocation.getCurrentPosition(
(position) => {
bdcApi = bdcApi +
"?latitude=" + position.coords.latitude +
"&longitude=" + position.coords.longitude +
"&localityLanguage=en";
getApi(bdcApi);
},
(err) => {
getApi(bdcApi);
}, {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
});
})
function getApi(bdcApi) {
Http.open("GET", bdcApi);
Http.send();
Http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
result.innerHTML = this.responseText;
var results = this.responseText
document.getElementById("city").innerHTML = results.city
}
};
}
</script>
You need to convert the API's text response into an actual Javascript object before you attempt to access its members.在尝试访问其成员之前,您需要将 API 的文本响应转换为实际的 Javascript object。 You can convert JSON text into a Javascript object by using JSON.parse()
.您可以使用JSON.parse()
将 JSON 文本转换为 Javascript object。
Try this instead:试试这个:
const results = JSON.parse(this.responseText);
(As a side note, if you don't need to support Internet Explorer, you will likely be better off using the newer and easier-to-use fetch
instead of XMLHttpRequest
.) (附带说明,如果您不需要支持 Internet Explorer,则最好使用更新且更易于使用的fetch
而不是XMLHttpRequest
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.