Home  >  Article  >  Web Front-end  >  How to Retrieve the Specific Error Response Text from a jQuery $.ajax Request?

How to Retrieve the Specific Error Response Text from a jQuery $.ajax Request?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 22:18:30262browse

How to Retrieve the Specific Error Response Text from a jQuery $.ajax Request?

Retrieving jQuery $.ajax Error Response Text

jQuery $.ajax requests can receive error responses from the server. While the default error handler only provides a generic 'error' message, it is possible to retrieve the actual response text containing server-specific error details.

Consider the following scenario:

A server sends an HTTP 500 error with the response text "Gone to the beach" to an $.ajax request. However, the jQuery error handler only displays 'error' as a message.

To resolve this issue, we can utilize the xhr.responseText property within the error function. The responseText contains the actual server response, including the error message:

<code class="javascript">error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}</code>

In this example, the responseText is parsed as JSON to access the error message with the "Message" property. The alert will then display the actual error response, "Gone to the beach" in our case.

The above is the detailed content of How to Retrieve the Specific Error Response Text from a jQuery $.ajax Request?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn