6

The essence of my question is this: If I issue a $.ajax request to my server for server-side validation -- how should I expect to handle the validation response? I see myself as having two options:

//  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);
   }
}

The former example assumes that my server's controller has a try/catch which consumes any server-side exceptions. It then takes any exceptions and returns them as part of the json success object. The latter allows the server's exception to bubble up through and be caught in the ajax error handler.

Personally, I thought I preferred the latter. However, I just encountered an issue with remoting -- if our server's security settings aren't relaxed then the error message gets hidden as a 'Runtime Error' and reading the error information from the ajax's onerror event handler becomes impossible.

I would like to avoid that issue, I need to always be able to read my errors, but it seems really wrong to have my ajax request always return successful.

How is this normally handled?

[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
        });
}

This versus setting success to false and setting an error property to the error message.

4

2 回答 2

4

我在我的系统中做了一些非常相似的事情。成功总是返回如下数据:

$data['success'] = array(/* your data to be served back to the page */); //PHP

而错误总是像这样:

$data['errors'] = array(/* your error data */); //PHP

您可以设置标志以在控制器 catch() 语句中查找异常代码,以过滤错误消息的类型。在您的 JS 代码中,您只需执行以下操作:

// JS
$.ajax({success:function(data) {
    if (data.success !== undefined) {}
    else if (data.errors !== undefined) {}
}});

您可以更疯狂地将它们添加为全局 AJAX 处理程序,也可以通过将此代码添加到$(document).ajaxComplete();回调中。

您可以并且应该为 ajax 错误回调设置一个单独的处理程序,因为这可能包括您的控制器代码无法控制的情况(404 错误、服务器无法访问等)。

于 2013-07-16T17:04:10.407 回答
0

我想你可以试试这个来检查 ajax 调用的错误。

$.ajax({
   url: 'controller/action',
   data: {},
   success: function(){
   },
   error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.status);
    }
}

根据jqXHR.status值,您可以显示自定义错误消息。

于 2013-07-16T17:20:31.547 回答