简体   繁体   中英

Parsing JSON string with jQuery.parseJSON()

So, this should be simple in my mind... I have a valid JSON string being returned through an Ajax post:

{"success":true,"message":"Thank you! We value your feedback."}

And I'm simply trying to alert my "message" value onto my resulting post return:

success: function (result) {
   alert(result);
   var obj = $.parseJSON(result);
   alert(obj.message);
  },
error: function (req, status, error) {
   alert("Sorry! We could not receive your feedback at this time.");
  }

My "obj" attributes somehow aren't being recognized..... I've validated the JSON string to make sure it was valid, so what am I missing here?

You shouldn't need to parse your JSON. Set the dataType attribute to json and jQuery will parse it for you. Then, result is essentially your JSON and you can do alert(data.message); .

jQuery.ajax({
  ...
  dataType: "json",
  success: function(data) {
     alert(data.message);
  },
  ...
});

What may be happening in this case is that jQuery is already treating your result as a JSON object. If your server returns the data with a MIME type of application/json , jQuery will detect that you're returning JSON and set the result to a javascript object rather than a string.

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