サーバーから返された 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"}