简体   繁体   English

javascript json object 值返回未定义

[英]javascript json object value returns undefined

I realize there are 100's of posts about javascript json objects.我意识到有 100 个关于 javascript json 个对象的帖子。 And all of them imply my code should work, so I am sure I am missing something really stupid.所有这些都暗示我的代码应该可以工作,所以我确信我错过了一些非常愚蠢的东西。 Every attempt to access the json object's key value results in undefined even though the json.parse works fine.每次尝试访问 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']);
            
         }
    };

This results in the following for alerts:这会导致以下警报:

"{\"exists\":\"True\"}"
{"exists":"True"}
undefined
undefined

What incredibly obvious and dumb thing am I missing?我错过了什么非常明显和愚蠢的事情? I even attempted to use my exact string in w3schools example and it appears to work fine https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_dot我什至尝试在 w3schools 示例中使用我的确切字符串,它似乎工作正常https://www.w3schools.com/js/tryit.asp?filename=tryjson_object_dot

Thank you in advance.先感谢您。

I don't know how it was working using your browser, I got a set of syntax errors when I was trying to test your code.我不知道它是如何使用你的浏览器工作的,我在尝试测试你的代码时遇到了一组语法错误。 Finally only this code was working最后只有这段代码有效

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

but common way to use it但常见的使用方式

    xhr.onload = () => {
        resp= xhr.response;
    }
     xhr.onerror = () => {
        console.log("error " + xhr.status);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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