开发者

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 al开发者_StackOverflow社区ert 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜