开发者

How should error corresponding to an AJAX request be passed to and handled at the client-side?

I have the following form for my users to change their email addresses.

<form enctype="multipart/form-data" id="email_change_form" method="post" action="/my_account/">
<table> 
<tr> 
  <td> 
    <label for="id_email">E-mail address</label>:
  </td> 
  <td> 
    <input name="email" value="a@a.com" maxlength="75" type="text" id="id_email" size="30" /> 
  </td> 
  <td class="error_email">
  </td> 
</tr> 
</table> 
<input type="hidden" name="form_id" value="email_change_form" />开发者_开发问答; 
</form>

Upon clicking the save button (whose code is not shown), the form gets posted to the server ajaxly with the following jQuery code:

$(".save_button").click(function() {
    var $form = $("#email_change_form")
    url = $form.attr("action");

    $.post(url, $form.serialize(), 
      function(data) {
          //upon success, the server returns the new email (data.email) in a json dictionary. 
        },
        "json"
      );      
    }
  })

Once the server received the POST, it needs to verify that the new email does not already exist in the database (ie. email needs to be unique). Say the server detects a duplicate email, I am not sure how to communicate the error back to the client-side. I was tempted to add an entry "duplicate_email: true" to the json dictionary and return it to the client-side. I, somehow, feel that this isn't the right approach.

Please advise the right approach(es) for this scenario. How should the server pass the error back to the client-side? And how should the error be captured at the client-side? Thanks.


If you want to do it the Right Way™, make your services RESTful. In this case, the appropriate status code is probably "409 Conflict", which Wikipedia defines as "Indicates that the request could not be processed because of conflict in the request, such as an edit conflict". (See also REST HTTP status codes for failed validation or invalid duplicate.)

So have your server output a "409 Conflict" header, and in your client, check status. $.post() won't do it as you can only register a success handler, so you'll need to use $.ajax() like this:

$.ajax({
  statusCode: {
    409: function() {
      alert('duplicate');
    }
  }
});


The best practice would probably be to return an error object like this:

{error:true,
 errorCode:123,
 errorMessage:"Duplicate Email",
 errorDescription:"The email you entered (john@johndoe.com) already exists"
}

Then you can track a list of error codes/messages specific to your application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜