Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-28 22:18:30
Original
279 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template