简体   繁体   中英

How do I access JSON data returned from an AJAX request?

I have a JavaScript function that receives data from an AJAX call to the server.

function dataReceiver() {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
        // Everything is good, the response was received.
        if (httpRequest.status === 200) {
            //console.log( JSON.parse(this.responseText) );
            let data = JSON.parse(this.responseText);
            console.log("1) " + data["key1"]);
            console.log("2) " + data['key1']);
            console.log("3) " + data.key1);

        } else {
            // There was a problem with the request.
            alert("Error: HTTP request status " + httpRequest.status);
        }
    } else {
        // Not ready yet.
        console.log("Request status: " + httpRequest.status);
    }
}

The data is sent in JSON format, and it is being received correctly. The commented console.log() line returns

{"key1": "stringValue1", "key2": "stringValue2", "key3": intValue}

with keys and values exactly as expected.

However, I cannot access this data. The three uncommened console.log() lines show the ways I've tried to get access to this data, and the console shows

  1. undefined
  2. undefined
  3. undefined

How do I access JSON data returned by an AJAX request?

There are several other questions on this site with similar problems, but all that I can find involve things that don't apply to this situation, like React, jQuery, or PHP. This is plain JavaScript.

Edit: If I don't try parsing the JSON, the raw response comes back as

console.log( this.responseText );
-> "{\"key1\": \"stringValue1\", \"key2\": \"stringValue2\", \"key3\": intValue}"

which is just the expected JSON object with escape backslashes for the double-quotes.

The function dataReceiver() shown in the question is the correct way to access JSON data returned from an AJAX request.

In this case, the error results from the sending function double-encoding the returned data as JSON. The first encoding converts the data into a string for transmission, which is how it's supposed to work. The second encoding then adds escape characters to that string, which breaks the encoding.

The raw JSON logged by console.log( this.responseText ); should not contain escape slashes . This is the clearest indicator of the error that the data has been JSON-encoded twice.

In principle, this error might occur using any method of sending data from the server. In this particular case, the data was sent from a Django view using

return JsonResponse(json.dumps(response), safe=False)

where I intended Python's json.dumps() function to perform the JSON-encoding; however, Django's built-in JsonResonse() also performs JSON-encoding, which is sort of obvious when you think about it, but I managed not to think about it; hence the double JSON-encoding. Simplifying this to

return JsonResponse(response, safe=False)

allowed the data to transmit and be interpreted correctly by the receiving JavaScript function.

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