jQuery处理JSON响应

AnA*_*ice 0 javascript jquery json

我从服务器响应中得到以下信息:

{"invalid_emails":["adsasdasd"],"result":"success","valid_emails":["jobs@apple.com"]}
Run Code Online (Sandbox Code Playgroud)

但是这个错误呢?

            $.ajax({
                type: 'POST',
                url: '/users/invitation',
                data: $('#user_invitation_new').serialize(),
                success: function(e) {
                    jsonObject = jQuery.parseJSON(e);
                    jsonObject.valid_emails
                    jsonObject.invalid_emails
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:Uncaught TypeError:无法读取null的属性'valid_emails'

Dav*_*ard 6

正如Jason和Jonathon所提到的,你不应该手动反序列化JSON.根据您使用的jQuery版本,jQuery将根据响应的content-type标头自动反序列化JSON.所以,你可能正在尝试$ .parseJSON()那些已经是对象的东西,而不是JSON字符串.

为了确保jQuery为您执行此自动反序列化,请dataType在$ .ajax()调用中添加一个参数:

$.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);
  }
});
Run Code Online (Sandbox Code Playgroud)