简体   繁体   中英

JavaScript JSON object not parsing

Here's my JS code from a success section of an AJAX call:

success: function(msg){
    var data = JSON.parse(JSON.stringify(msg));
    $("#searchResults").html(data + " Value for 'a': " + data.color + "\nValue for 'b': " + data.message);
}

Here's what's printed on the page:

{"color":"Yellow","message":"Pending"} Value for 'a': undefined Value for 'b': undefined

Why are they undefined?

console.log data似乎仍然是字符串,如@Musa所说,您需要删除JSON.stringify

If your ajax response is JSON you should explicitly state so in the request so that it will be parsed automatically for you by jQuery.ajax . dataType: 'json'

$.ajax({
...
    dataType: 'json',
    success: function(data){
        $("#searchResults").html(" Value for 'a': " + data.color + "\nValue for 'b': " + data.message);
    }
...

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