AJAX - get response body in success and error

2019-04-19 08:42发布

问题:

I am apologize for the stupid question, but I need your help. I need to get information about response inside AJAX.

$.ajax({
          type: "POST",
          url: '/register',
          data : registerRequestJSON,
          contentType:"application/json",
          success: function(data){
              $("#register_area").text();// need to show success
          },
          error: function(err) {
            $("#register_area").text("@text"); // @text = response error, it is will be errors: 324, 500, 404 or anythings else
          }
    });

How can I use response body? (documentation Jquary.Ajax is not working at the momment)

回答1:

The first param to error handler is jqxhr, it has the property responseText which will give the response body.

$.ajax({
          type: "POST",
          url: '/register',
          data : registerRequestJSON,
          contentType:"application/json",
          success: function(data){
              $("#register_area").text();// need to show success
          },
          error: function(jqxhr) {
            $("#register_area").text(jqxhr.responseText); // @text = response error, it is will be errors: 324, 500, 404 or anythings else
          }
    });