How to get the jQuery $.ajax error response text?

2018-12-31 22:04发布

I am sending an error response to my jQuery. However, I can not get the response text (in the example below this would be Gone to the beach)

The only thing jQuery says is 'error'.

See this example for details:

php

<?
    header('HTTP/1.1 500 Internal Server Error');
    print "Gone to the beach"
?>

jQuery

$.ajax({
    type:     "post",
    data:     {id: 0},
    cache:    false,
    url:      "doIt.php",
    dataType: "text",
    error: function (request, error) {
        console.log(arguments);
        alert(" Can't do because: " + error);
    },
    success: function () {
        alert(" Done ! ");
    }
});

Now my result ist:

log:

 [XMLHttpRequest readyState=4 status=500, "error", undefined]

alert:

Can't do because: error

Any ideas?

11条回答
梦醉为红颜
2楼-- · 2018-12-31 22:20

Try:

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}
查看更多
零度萤火
3楼-- · 2018-12-31 22:20

For me, this simply works:

error: function(xhr, status, error) {
  alert(xhr.responseText);
}
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 22:20

The best simple approach :

error: function (xhr) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
查看更多
像晚风撩人
5楼-- · 2018-12-31 22:24

Look at the responseText property of the request parameter.

查看更多
泛滥B
6楼-- · 2018-12-31 22:29

If you're not having a network error, and wanting to surface an error from the backend, for exmple insufficient privileges, server your response with a 200 and an error message. Then in your success handler check data.status == 'error'

查看更多
登录 后发表回答