【发布时间】:2014-10-03 18:41:54
【问题描述】:
我正在通过$.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)"
所以我认为它正在尝试解析 JSON 而不是 html。我不明白,因为我已将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 Bout 回复)
$.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 控制台)并检查了响应的实际返回类型(
Content-Type)? -
@JanakaBandara 我更新了我的问题为什么信息。
标签: jquery html ajax json asp.net-mvc-4