当我尝试解析从服务器返回的 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
我注意到,当 header Content-type 未设置为“application/json”时,JSON.parse 工作正常,但如果 Content-type 设置为 json,则 JSON.parse 不起作用。知道为什么会发生这种情况吗?
不工作的代码:
Controller 代码:
$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"}
有效的代码
Controller :
$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"}
最佳答案
当您没有为 $.ajax
调用指定 dataType
选项时,jQuery 会尝试根据 Content-Type
解析响应code> 响应中返回的 header 。
因此,当您没有为 dataType
指定任何内容,并且没有为 Content-Type
header 指定任何特殊内容时,response
会被解析为文本。
当您为 dataType
指定任何内容,并为 Content-Type
header 指定“json”时,response
将被解析为 JSON (Javascript对象字面量)。
当您将 dataType
指定为“json”时,无论 Content-Type
header 是什么,都会解析 response
作为 JSON(Javascript 对象文字)。
尝试将对象文字传递给 JSON.parse
将失败,因为它只接受字符串。
因此,您需要确定要设置的内容以及要尝试调用的内容 (JSON.parse
),并使用正确的组合。
关于jquery - 当 content-type 设置为 application/json 时,JSON.parse() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15940658/