简体   繁体   中英

javascript json object value returns undefined

I realize there are 100's of posts about javascript json objects. 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.

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

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

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