1

I use the jQuery Ajax request the list:

$.get('http://localhost:8000/amodel/list2/', function(data, status){

    console.log(status, data); // if fails, there do not console out anything.  

});

there is no status code, how to judge the request is success or fail?.

How to optimize the jQuery Ajax http request?

My requirement:

  1. if fail it should execute the fail handler function.
  2. if there is a status code, that's better.
sof-03
  • 2,255
  • 4
  • 15
  • 33
  • 2
    Possible duplicate of [How do I get the HTTP status code with jQuery?](https://stackoverflow.com/questions/2955947/how-do-i-get-the-http-status-code-with-jquery) – peeebeee Jul 13 '18 at 10:15

2 Answers2

6

Change your ajax request like this

$.get('http://localhost:8000/amodel/list2/').done(function(data){
     // Your Success method
}).fail(function(data){
    // Fail method
  console.log(data.responseText)
});
Abhishek
  • 972
  • 3
  • 12
  • 24
1

Why not use $.ajax instead of $.get. The more clear version. Remember: $.get is just a wrapper to the $.ajax. Internally $.ajax is always called. What benefit $.ajax gives is that it is more configurable than $.get and $.post.

 $.ajax({
                        type: "GET",
                        url: "/amodel/list2",
                        success: function (r) { 
                        //Do stuff here. This will only execute when request succeed
                       //r in function parameter is response
                         },
                     error: function (r, textStatus, errorThrown) {
                    //i am using this error handler in ajax method to get 
                    //the status code in my project. hope this will work for you as well
                         if (r.status === 403) {//do stuff}
                         if (r.status === 470) {}
                    }
                    }).fail(function (e) {
                        console.log(e.responseText);
                    }).always(function () {
                      //Do stuff here which you want always to execute.
                     // Like hiding ajax loader even if request fails etc
                    });
Ahmad
  • 887
  • 7
  • 21