jQuery的处理JSON响应
问题描述:
我有来自服务器的响应如下:jQuery的处理JSON响应
{"invalid_emails":["adsasdasd"],"result":"success","valid_emails":["[email protected]"]}
但这个错误?
$.ajax({
type: 'POST',
url: '/users/invitation',
data: $('#user_invitation_new').serialize(),
success: function(e) {
jsonObject = jQuery.parseJSON(e);
jsonObject.valid_emails
jsonObject.invalid_emails
我得到以下错误:遗漏的类型错误:无法读取空
答
贾森和乔纳森提到的,你不应该手动反序列化JSON的。根据您使用的jQuery版本,jQuery将根据响应的内容类型标题自动反序列化JSON。所以,你可能试图$ .parseJSON()这已经是一个对象,而不是一个JSON字符串。
要确保jQuery的为您完成此自动反序列化,一个dataType
参数添加到$阿贾克斯()调用:
$.ajax({
type: 'POST',
dataType: 'json',
url: '/users/invitation',
data: $('#user_invitation_new').serialize(),
success: function(response) {
console.log(response.valid_emails);
console.log(response.invalid_emails);
}
});
+0
+1用于指出内容类型标题 - 真的帮助我了! – adamdport 2012-10-02 16:41:35
答
的特性“valid_emails”你可以不必解析JSON,因为它已经是一个JSON对象。尝试做
var emails = e.valid_emails;
如果仍然无法正常工作,包括在您.ajax()
声明dataType: 'json'
。
答
如果您的服务器使用JSON响应,那么您应该运行jQuery.parseJSON(e);
。该e
参数可能已经成为了那么试试这个为您的成功处理程序:
success: function(e)
var valEmails = e.valid_emails,
invalEmails = e.invalid_emails;
};
答
刚刚尝试包括
dataType: 'json',
你能看懂其他属性? – 2010-12-17 01:00:50