[英]javascript json object value returns undefined
我意識到有 100 個關於 javascript json 個對象的帖子。 所有這些都暗示我的代碼應該可以工作,所以我確信我錯過了一些非常愚蠢的東西。 每次嘗試訪問 json 對象的鍵值都會導致未定義,即使 json.parse 工作正常。
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var resp = JSON.parse(this.responseText);
alert(this.responseText);
alert(resp.toString());
alert(resp.exists);
alert(resp['exists']);
}
};
這會導致以下警報:
"{\"exists\":\"True\"}"
{"exists":"True"}
undefined
undefined
我錯過了什么非常明顯和愚蠢的事情? 我什至嘗試在 w3schools 示例中使用我的確切字符串,它似乎工作正常https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_dot
先感謝您。
我不知道它是如何使用你的瀏覽器工作的,我在嘗試測試你的代碼時遇到了一組語法錯誤。 最后只有這段代碼有效
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var resp = xhr.response;
alert(JSON.stringify( resp)); //{"exists":"True"}
alert(resp.exists); //"True"
alert(resp['exists']); //"True"
}
};
xhr.send();
但常見的使用方式
xhr.onload = () => {
resp= xhr.response;
}
xhr.onerror = () => {
console.log("error " + xhr.status);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.