2014-03-07 133 views
1

我正在使用AJAX請求到submit a form登錄。Parserror在AJAX請求中,表單提交

$.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,看起來好像是jsonresponseText。我不知道還有什麼要做。

(不要將此問題作爲一個重複的,我這樣做搜索過,沒有問題解決了我的問題)

編輯 新增responseText

responseText: "↵{"success":true,"error":false}" 

firefox

"\r\n{"success":true,"error":false}" 

EDIT2

json_encode(array(..)) 

介紹\r\n,但我不知道爲什麼。

+0

的URL返回什麼?只是'串'?那麼它不是一個有效的JSON – SajithNair

+0

你可以添加'responseText'或螢火蟲屏幕截圖嗎? – Girish

+0

用回覆文本編輯了問題 – steo

回答

1

是意外的字符響應,請在服務器端使用json_encode函數之前的ob_start函數。 這是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響應的問題,請參閱打擊圖像更好地瞭解 enter image description here new line錶殼(紅色標記)將在您的服務器代碼..如果您可以刪除new line該問題將得到解決。

其他溶液

刪除頭(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) 
});