jQuery AJAX error handling

前端 未结 4 1752
半阙折子戏
半阙折子戏 2020-12-16 05:56

I\'ve searched the questions on here, but I don\'t have a good understanding of how to use the error handling in jQuery\'s AJAX (im a noob, so it just really doesn\'t make s

4条回答
  •  眼角桃花
    2020-12-16 06:18

    The jQuery AJAX error handling is implemented to handle if the HTTP Request has an error not if your script is returning "error" or "success". If the server throws an error (404 Not Found or 500 Server Error as an example) then it will trigger the error functions of jQuery. It can be handled a few ways, but one nice way is to show a div letting the user know there was an error.

    HTML

    
    

    jQuery

    $(function(){
       $("#error").ajaxError(function(){
          var $error = $(this);
          $error.slideDown(500, function(){
              window.setTimeout(function(){
                  $error.slideUp(500);
              }, 2000);
          }); 
       });
    });
    

    If an error occurs, none of your "success" methods will fire, and that div will slide down, wait 2 seconds, then slide back up.

    Testing your script for errors

    As I mentioned what you described sounds like your server script is sending "error" or "success" or something similar back to the client.

    If you are using a $.post, for example, your error handling code might look like this:

    $.post('/your/url', { save_me: true }, function( data ){
       if(data == "error"){ 
          // handle error
       } else {
          // handle success
       }
    }
    

提交回复
热议问题