Home > Web Front-end > JS Tutorial > body text

How to Retrieve Error Response Text in jQuery $.ajax Requests?

Susan Sarandon
Release: 2024-10-27 09:11:30
Original
729 people have browsed it

How to Retrieve Error Response Text in jQuery $.ajax Requests?

Retrieving Error Response Text using jQuery $.ajax

When sending an error response to a jQuery AJAX request, it can be challenging to access the response text. By default, jQuery only provides the error status instead. To retrieve the actual response text, the following solution can be implemented:

Modify the error callback function in the jQuery AJAX request as follows:

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

In this updated error callback function:

  • The xhr.responseText property contains the full error response text.
  • eval is used to parse the response text as JSON (assuming the response is in JSON format).
  • The err.Message property is then accessed to retrieve the desired error message.

By implementing this change, the error callback function will now receive the parsed error response as the err argument. You can then access the error message (in this case, "Gone to the beach") through err.Message and display it accordingly.

The above is the detailed content of How to Retrieve Error Response Text in jQuery $.ajax Requests?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!