我通過$.ajax()
方法提交表單。我的要求是這樣的:jQuery ajax請求處理不同類型的響應
$.ajax(url, {
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "html json",
data: formData,
headers: {
"X-Requested-With": "XMLHttpRequest"
}
}).done(function (result) {
//handle correct json response or html response
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown.stack);
});
當服務器返回一個JSON響應時,所有的工作都被忽略。但是,當響應是HTML格式,執行fail()
回調(響應的狀態代碼是200 - OK)和errorThrown.stack爲這個值:
"SyntaxError: Unexpected token <
at Object.parse (native)
at jQuery.extend.parseJSON (http://localhost/Scripts/jquery-1.10.2.js:550:23)
at ajaxConvert (http://localhost/Scripts/jquery-1.10.2.js:8429:19)
at done (http://localhost/Scripts/jquery-1.10.2.js:8185:15)
at XMLHttpRequest.jQuery.ajaxTransport.send.callback (http://localhost/Scripts/jquery-1.10.2.js:8778:8)"
所以我認爲它正試圖HTML的解析JSON,而不是。我不明白,因爲我已經設置了dataType
選項"html json"
...
以下是關於請求/響應的一些信息:
請求頭
Accept:text/html, */*; q=0.01
Accept-Encoding:gzip,deflate
Accept-Language:pt-PT,pt;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:2386
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With:XMLHttpRequest
響應頭
Cache-Control:private, s-maxage=0
Content-Length:56392
Content-Type:text/html; charset=utf-8
Date:Fri, 03 Oct 2014 09:52:13 GMT
Server:Microsoft-IIS/8.5
Vary:Accept-Encoding
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:4.0
X-Powered-By:ASP.NET
這是爲什麼發生了什麼?
解決方案(基於@Oscar布特響應)
$.ajax(url, {
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "html",
data: formData,
headers: {
"X-Requested-With": "XMLHttpRequest"
}
}).done(function (result) {
try {
var jsonResult = $.parseJSON(result);
//handle json result
} catch (e) {
$("#myDiv").html(result); //handle html result
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown.stack);
});
我想用try/catch
是不是最好的方法,所以我聽其他選項。
你分析實際的請求和響應(例如使用瀏覽器的Web控制檯),並檢查響應('內容Type')的實際返回類型? – 2014-10-03 09:48:18
@JanakaBandara我更新了我的問題,爲什麼信息。 – amp 2014-10-03 09:55:55