Sea*_*son 5 ajax jquery exception-handling
我的问题的实质是:如果我向服务器发出$ .ajax请求以进行服务器端验证 - 我应该如何处理验证响应?我认为自己有两种选择:
// Server handled error:
$.ajax({
url: 'controller/action',
data: {},
success: function(response){
console.log("Error:", response.error);
}
}
// Server unhandled error:
$.ajax({
url: 'controller/action',
data: {},
success: function(){
},
error: function(error){
console.log("Error:", error);
}
}
Run Code Online (Sandbox Code Playgroud)
前一个示例假设我的服务器控制器有一个try/catch,它消耗任何服务器端异常.然后它接受任何异常并将它们作为json成功对象的一部分返回.后者允许服务器的异常冒泡并在ajax错误处理程序中捕获.
我个人认为我更喜欢后者.但是,我刚刚遇到远程问题 - 如果我们的服务器的安全设置没有放松,那么错误消息会被隐藏为'运行时错误',并且从ajax的onerror事件处理程序中读取错误信息变得不可能.
我想避免这个问题,我需要始终能够读取我的错误,但让我的ajax请求始终返回成功似乎是错误的.
这通常如何处理?
[HttpPost, AjaxOnly]
public ActionResult ChangePassword(ChangePasswordDialogModel model)
{
string error = string.Empty;
if (model.NewPassword == model.NewPasswordConfirm)
{
using (var service = new SecurityServicesSoapClient())
{
error = service.ChangePassword(SessionManager.Default.User.UserName, model.OldPassword,
model.NewPassword);
}
}
else
{
error = "New Password and Confirm do not match. Please re-enter";
}
if (!string.IsNullOrEmpty(error))
throw new Exception(error);
return Json(new
{
success = true
});
}
Run Code Online (Sandbox Code Playgroud)
这与将成功设置为false并将错误属性设置为错误消息相对.
I do something quite similar in my system. Success always returns data like:
$data['success'] = array(/* your data to be served back to the page */); //PHP
Run Code Online (Sandbox Code Playgroud)
whereas errors are always done like:
$data['errors'] = array(/* your error data */); //PHP
Run Code Online (Sandbox Code Playgroud)
You can set flags to look for exception codes in your controller catch() statements to filter types of error messages. In your JS code you just do:
// JS
$.ajax({success:function(data) {
if (data.success !== undefined) {}
else if (data.errors !== undefined) {}
}});
Run Code Online (Sandbox Code Playgroud)
You can get crazier and add them as global AJAX handlers as well by adding this code to a $(document).ajaxComplete(); callback.
You can and should have a separate handler for the ajax error callback, because that can include situations that your controller code has no control over (404 errors, server unreachable, etc).