Javascript AJAX请求中的语法错误,表单提交
我正在使用Javascript AJAX请求中的语法错误,表单提交,javascript,php,jquery,ajax,json,Javascript,Php,Jquery,Ajax,Json,我正在使用AJAX请求submitaformlogin $.post(url, {data: JSON.stringify( {obj: value} )}, 'json') .fail(function(){ console.log(typeof arguments[0].responseText) //logs 'string' //console.log(JSON.parse(arguments[0].responseText)) // decommented logs
AJAX
请求submit
aform
login
$.post(url, {data: JSON.stringify( {obj: value} )}, 'json')
.fail(function(){
console.log(typeof arguments[0].responseText) //logs 'string'
//console.log(JSON.parse(arguments[0].responseText)) // decommented logs "unexpected token"
console.log(arguments)
});
我要走了
1: "parsererror"
2: SyntaxError
message: "Unexpected token "
..
..
我还设置了标题(“Content-type:application/json”)
,但没有解决问题,
我还使用json\u encode
作为服务器端响应
我得到了status:200
,而且似乎是正确的json
responseText
。我不知道还能做什么
(不要将此问题标记为重复问题,我已搜索过,没有问题解决了我的问题)
编辑
添加了responseText
chrome
responseText: "↵{"success":true,"error":false}"
firefox
"\r\n{"success":true,"error":false}"
EDIT2
json_encode(array( .. ))
介绍
\r\n
但我不知道为什么。↵
是响应中意外的字符,请在服务器端的json_encode函数之前使用ob_start
函数。
↵代码>这是输入
键代码,请从响应中删除
ltrim(json_encode($response_arr), "\r\n"); // this would be useful in php code
//
到
ajax响应中的问题,请参阅blow image以获得更好的理解
新行
您的服务器代码中将有一个大写字母(红色标记)。。如果可以删除新行
,问题将得到解决
其他解决方案
删除标题(Content-type:application/json
),并在jQuery代码中使用jQuery.parseJSON(jQuery.trim(response))
ajax代码
$.post(url, {data: JSON.stringify( {obj: value} )}, function(response){
var data = jQuery.parseJSON(jQuery.trim(response));
console.log(data);
})
.fail(function(){
console.log(typeof arguments[0].responseText) //logs 'string'
//console.log(JSON.parse(arguments[0].responseText)) // decommented logs "unexpected token"
console.log(arguments)
});
url返回什么?只是“字符串”?如果添加responseText
或firebug屏幕截图,则这不是一个有效的json?请先用响应文本编辑问题以验证json数据。检查json数据是否有效。。。听起来你的json数据有点不对劲。我验证了我在开发者工具的“网络”选项卡中得到的响应,它似乎是有效的。
responseText: "{"success":true,"error":false}"
$.post(url, {data: JSON.stringify( {obj: value} )}, function(response){
var data = jQuery.parseJSON(jQuery.trim(response));
console.log(data);
})
.fail(function(){
console.log(typeof arguments[0].responseText) //logs 'string'
//console.log(JSON.parse(arguments[0].responseText)) // decommented logs "unexpected token"
console.log(arguments)
});