在尝试解析从服务器返回的 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 则不起作用。知道为什么会发生这种情况吗?
不工作代码:
控制器代码:
$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 与正常工作的相同
标题:
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"}