Ajax解析json字符串返回undefined,

我发送一个post数据来获取一个json字符串:

我的JSON字符串:

{"error":false,"success":"Added Website","website_id":"12"} 

我的Ajax请求:

 $('.publsher_add_website').on("submit", function() { show_loader(); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: $(this).serialize(), success: function(data) { if (data.success == false) { ajax_error(data.error); hide_loader(); } else { console.debug(data); console.log(data.error); console.log(data.success); console.log(data.website_id); location.href = site_url + "publisher/websites?added=" + data.website_id + "#modal-verify"; hide_loader(); } }, error: function() { hide_loader(); } }); return false; }); 

现在,当我去使用返回的data所有这些都是未定义的。我使用过:

 console.debug(data); 

它返回上面的json字符串,但如果我尝试单独访问它们:

 data.error; data.success; data.website_id; 

他们都回归undefined为什么会这样? 我该如何解决?

您没有在$.ajax提供dataType ,因此AJAX将响应视为string ,而不是对象。 因此,在success函数中,首先执行此操作:

 success: function(data) { data = JSON.parse(data); 

尝试将json字符串解析为json对象以获取值:

 data = JSON.parse(data);