我想知道如何使用具有 http 兼容方法的最新 jquery ajax 请求来处理数据传输和处理错误的正确方法。
我注意到,当服务器端发生未处理的异常,并且我没有在 http 协议中指定我期望的数据类型时,成功方法调用并且客户端收到 200 OK 响应,好像没有发生任何错误:
$.ajax({
url: action,
type: 'POST',
data: jsondata,
success: function (data, textStatus, xhr) {
// i'm here now
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
如果我指定类型,我期望为 exaple json,调用一个 ajax错误函数。这是因为stack trace默认没有序列化为json,所以解析会失败:
$.ajax({
url: action,
type: 'POST',
dataType: 'json',
data: jsondata,
contentType: 'application/json; charset=utf-8',
success: function (data, textStatus, xhr) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// but now I'm here
}
});
现在它也是 200 OK,但是调用了一个错误(不成功)。
处理异常处理的更好方法是什么。我应该指定类型,在我看来更 RESTFull,还是让它不指定,并且总是跳到成功?
我是否应该始终在服务器端将 ajax 方法包装成try{}catch(){}
块,并传递适当类型的错误,客户端要求我返回?
[HttpPost]
public NJsonResult Execute()
{
try
{
// do some logic if you do not mind
if (success)
{
return new NJsonResult(new {status = "success"});
}
return new NJsonResult(new { status = "error" });
}
catch(Exception e)
{
return new NJsonResult(new { status = "error" });
}
}
$.ajax({
type: 'POST',
url: action,
dataType: 'json',
data: jsondata,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status == "success") {
}
else (data.status == "error") {
}
}
Mabye 我应该总是关心可预测的错误并且不关心异常,并且没有指定任何类型吗?
[HttpPost]
public NJsonResult Execute()
{
// do some logic if you do not mind
if (success)
{
return new NJsonResult(new {status = "success"});
}
return new NJsonResult(new { status = "error" });
}
$.ajax({
type: 'POST',
url: action,
data: data,
success: function (data) {
if (data.status == "success") {
}
else {
// handle even exceptions, because content-type in not specified
}
}
});
错误功能和正确 http 状态代码的位置在哪里(并不总是 200 OK)
现在,我实现了一个全局钩子来拦截未处理的异常:
$(document).ready(function () {
$.ajaxSetup({
error: function (XMLHttpRequest, textStatus, errorThrown) {
// handle it if you dare
}
});
});
并始终使用contentType和dataType ajax 属性指定内容类型并接受标头。我不使用块 - 我不关心逻辑异常行为。我只是将它登录到Global.asax并将其进一步传递给响应。try{}catch{}
那么,就像这个问题的第一行一样,最好的方法是什么?还有其他想法吗?