尝试解析从服务器返回的JSON字符串时,我遇到了一个jquery(错误/错误):
Timestamp: 10/04/2013 21:05:12
Error: SyntaxError: JSON.parse: unexpected character
Source File: http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
Line: 3
并且我注意到,当标头Content-type未设置为'application / json'时,JSON.parse可以正常工作,但是如果Content-type设置为json,则JSON.parse无法正常工作。知道为什么会这样吗?
不起作用的代码:
控制器代码:
$response = array('data' => array('msg' => 'Form did not validate'), 'response_handler_fn' => 'sign_up_response_handler_fn');
$this->getResponse()->setHttpHeader('Content-type','application/json');
return $this->renderText(json_encode($response));
Javascript:
// ...
success: function( response ) {
var responseData = $.parseJSON(response);
}
标头
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection Keep-Alive
Content-Length 92
Content-Type application/json
Date Wed, 10 Apr 2013 20:05:12 GMT
Expires Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive timeout=15, max=100
Pragma no-cache
Server Apache
X-Powered-By PHP/5.3.5
响应:
{"data":{"msg":"Form did not validate"},"response_handler_fn":"sign_up_response_handler_fn"}
起作用的代码
控制器:
$response = array('data' => array('msg' => 'Form did not validate'), 'response_handler_fn' => 'sign_up_response_handler_fn');
return $this->renderText(json_encode($response));
Javascript与有效的JavaScript相同
标头:
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection Keep-Alive
Content-Length 92
Content-Type text/html; charset=utf-8
Date Wed, 10 Apr 2013 20:09:04 GMT
Expires Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive timeout=15, max=100
Pragma no-cache
Server Apache
X-Powered-By PHP/5.3.5
响应:
{"data":{"msg":"Form did not validate"},"response_handler_fn":"sign_up_response_handler_fn"}
最佳答案
当您未为dataType
调用指定$.ajax
选项时,jQuery尝试根据响应中返回的Content-Type
标头解析响应。
因此,当您没有为dataType
指定任何内容且为Content-Type
标头没有任何特殊内容时,response
将被解析为文本。
当您没有为dataType
指定任何内容,而为Content-Type
标头指定“ json”时,response
将被解析为JSON(Javascript对象文字)。
当将dataType
指定为“ json”时,Content-Type
标头没有关系,response
被解析为JSON(Javascript对象文字)。
尝试将对象文字传递给JSON.parse
将失败,因为它仅接受字符串。
因此,您需要确定要设置的内容和要调用的内容(JSON.parse
),并使用正确的组合。