Home > Web Front-end > JS Tutorial > How Can I Access AJAX Response Text Using Prototype's `onComplete` Handler?

How Can I Access AJAX Response Text Using Prototype's `onComplete` Handler?

Barbara Streisand
Release: 2024-12-12 12:41:11
Original
771 people have browsed it

How Can I Access AJAX Response Text Using Prototype's `onComplete` Handler?

Getting AJAX Response Text in Prototype

AJAX responses are often in text format, and retrieving this text is crucial for further processing. Prototype provides a convenient way to access this response text, but it requires a slight adjustment to the usual approach.

In the code snippet, the onComplete event handler is where the response text should be obtained. However, the "result" variable in the initial implementation is not accessible outside the onComplete function due to asynchronous operations.

To overcome this, Prototype's onComplete handler allows for a callback function as a parameter. This callback function is executed when the AJAX request is complete, and it can receive the responseText as an argument.

Here's the modified code:

somefunction: function(callback) {
  var result = "";
  myAjax = new Ajax.Request(postUrl, {
    method: 'post',
    postBody: postData,
    contentType: 'application/x-www-form-urlencoded',
    onComplete: function (transport) {
      if (200 == transport.status) {
        result = transport.responseText;
        callback(result);
      }
    }
  });
}
Copy after login

When calling somefunction, provide the callback function as an anonymous function:

somefunction(function (result) {
  alert(result);
});
Copy after login

This approach ensures that the response text is accessible in the callback function, allowing for further processing or display.

The above is the detailed content of How Can I Access AJAX Response Text Using Prototype's `onComplete` Handler?. 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