Best way to check if AJAX request was successful in jQuery

前端 未结 3 1402
挽巷
挽巷 2021-01-01 21:21

I\'ve been checking to make sure my AJAX requests are successful by doing something like this:

$.post(\"page.php\", {data: stuff}, function(data, status) {
          


        
3条回答
  •  一个人的身影
    2021-01-01 21:49

    jQuery considers "successful" in the way it is in the source code, of course. This does not include a status code of 404/500 and neither a timeout, since no status code has been returned in that case.

    You can check when exactly it returns "success":

    // If successful, handle type chaining
    if ( status >= 200 && status < 300 || status === 304 ) {
    
    ...
        // If not modified
        if ( status === 304 ) {
    
            statusText = "notmodified";
    ...
    
        // If we have data
        } else {
    
            try {
    ...
                statusText = "success"; // So: only when status code is in
                                        // the range 200 <= x < 300
    ...
            } catch(e) {
    ...
                statusText = "parsererror";
    ...
            }
        }
    

提交回复
热议问题