[英]Parserror in AJAX request, form submit
我正在使用AJAX
請求submit
form
登錄名。
$.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 "
..
..
我還設置了header("Content-type: application/json")
但它沒有解決問題,我還使用json_encode
作為服務器端響應。
我的status: 200
,似乎是正確的json
responseText
。 我不知道該怎么辦
(不要將此問題標記為重復,我確實在SO上進行了搜索,沒有一個問題解決了我的問題)
編輯添加了responseText
鉻
responseText: "↵{"success":true,"error":false}"
火狐
"\r\n{"success":true,"error":false}"
EDIT2
json_encode(array( .. ))
介紹\\r\\n
但我不知道為什么。
↵
是為了應對意外的字符,請使用ob_start
在服務器端json_encode功能之前功能。 ↵
這是enter
關鍵代碼,請從響應刪除
ltrim(json_encode($response_arr), "\r\n"); // this would be useful in php code
//
responseText: "↵{"success":true,"error":false}"
至
responseText: "{"success":true,"error":false}"
Ajax響應中的問題,請參見打擊圖像以更好地理解 服務器代碼中將包含
new line
(紅色標記)..如果可以刪除new line
該問題將得到解決。
其他解決方案
刪除header( Content-type : application/json
)並在jQuery代碼中使用jQuery.parseJSON(jQuery.trim(response))
。
阿賈克斯代碼
$.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)
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.