2010-08-25 163 views
1

所以,这应该是简单的在我的脑海...我有通过Ajax后返回一个有效的JSON字符串:解析JSON字符串jQuery.parseJSON()

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

我的“目标文件”属性在某种程度上是不被认可.....我已经验证了JSON字符串,以确保它是有效的,所以我在这里错过了什么?

回答

6

你不应该需要解析你的JSON。将dataType属性设置为json,jQuery将为您解析它。那么,result本质上是你的JSON,你可以做alert(data.message);

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

优秀!非常感谢! – denisb 2010-08-25 19:31:10

1

在这种情况下可能发生的情况是,jQuery已经将您的结果视为JSON对象。如果您的服务器返回MIME类型为application/json的数据,那么jQuery将检测到您返回JSON并将结果设置为JavaScript对象而不是字符串。