use*_*694 4 ajax jquery json content-type
我在尝试解析从服务器返回的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
Run Code Online (Sandbox Code Playgroud)
我注意到当标题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));
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
// ...
success: function( response ) {
var responseData = $.parseJSON(response);
}
Run Code Online (Sandbox Code Playgroud)
头
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
Run Code Online (Sandbox Code Playgroud)
响应:
{"data":{"msg":"Form did not validate"},"response_handler_fn":"sign_up_response_handler_fn"}
Run Code Online (Sandbox Code Playgroud)
有效的代码
控制器:
$response = array('data' => array('msg' => 'Form did not validate'), 'response_handler_fn' => 'sign_up_response_handler_fn');
return $this->renderText(json_encode($response));
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
响应:
{"data":{"msg":"Form did not validate"},"response_handler_fn":"sign_up_response_handler_fn"}
Run Code Online (Sandbox Code Playgroud)
Ian*_*Ian 10
如果未指定调用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),并使用正确的组合.
| 归档时间: |
|
| 查看次数: |
7245 次 |
| 最近记录: |