我正在创建内部管理站点的只读版本,并且希望让任何写入功能(在只读站点上返回403)都使用常规警报消息,但是会出现其他错误,仅警告从控制器返回的异常消息会很有帮助。
下面的jQuery代码有效,但是有一种方法可以跳过403的error
回调,而不必在所有地方添加if (xhr.status !== 403)
检查。我并不是想变得懒惰,它只是闻起来很有趣,而且我觉得我缺少明显的我应该做的事情。
$.ajaxSetup({
statusCode: {
403: function (err) {
alert('This function is not available on the read-only site. Contact so and so to fulfill your request.')
}
}
});
$.ajax({
url: 'controller/action',
type: 'POST',
data: postData,
dataType: 'json',
contentType: 'application/json',
traditional: true,
success: function (data) {
//
},
error: function (xhr, status, error) {
if (xhr.status !== 403) {
var err = xhr.responseJSON.Message
alert('Error: ' + err);
}
}
});
答案 0 :(得分:2)
似乎可以创建一个全局包装函数来处理常见错误(404、403),然后在其中处理特定于函数的内容。喜欢:
handleGlobalErrors = (cb) => {
return (xhr, status, error) => {
if (xhr.status !== 403) {
var err = xhr.responseJSON.Message
alert('Error: ' + err);
}
cb(xhr, status, error);
}
}
$.ajaxSetup({
statusCode: {
403: function (err) {
alert('This function is not available on the read-only site. Contact so and so to fulfill your request.')
}
}
});
$.ajax({
url: 'controller/action',
type: 'POST',
data: postData,
dataType: 'json',
contentType: 'application/json',
traditional: true,
success: function (data) {
// Normal Success Method
},
error: handleGlobalErrors((xhr, status, error) => {
// Other error-handling logic
})
});
也就是说,这是一个点问题的解决方案。您确实应该考虑使用像Angular,Vue或React这样的真正的MVC,因为那样就不需要混合使用View和Controller逻辑。