javascript - 使用 jQuery.parseJSON() 解析 JSON 字符串

标签 javascript jquery json

所以,这在我看来应该很简单......我有一个通过 Ajax post 返回的有效 JSON 字符串:

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

我只是想将我的“消息”值提醒到我返回的结果中:

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

我的“obj”属性以某种方式未被识别......我已经验证了 JSON 字符串以确保它是有效的,那么我在这里遗漏了什么?

最佳答案

您不需要解析 JSON。将 dataType 属性设置为 json,jQuery 将为您解析它。然后,result 本质上是您的 JSON,您可以执行 alert(data.message);

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

关于javascript - 使用 jQuery.parseJSON() 解析 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3569416/

相关文章:

javascript - 触发 ng-click 动态元素

javascript - 尝试使用 Knockout.js 显示包含集合的变量时出现问题

javascript - JS嵌套对象访问全局变量

javascript - 使用 Javascript 读取智能卡证书

javascript - 发现由于验证错误,表单未发布到服务器

jquery - 将错误列表从Sinatra传递到jQuery的错误处理程序?

jquery - 如果确认为 true,则调用另一个 jQuery 函数

PHP 或 jQuery/PHP 分页

iphone - -[__NSCFDictionary JSONRepresentation] : unrecognized selector sent to instance

jquery - 如何通过ajax将JSON数据传递给restful web服务以及如何获取JSON数据?