Home > Web Front-end > JS Tutorial > How Do I Retrieve and Use the Response from an XMLHttpRequest?

How Do I Retrieve and Use the Response from an XMLHttpRequest?

Susan Sarandon
Release: 2024-12-08 21:20:14
Original
989 people have browsed it

How Do I Retrieve and Use the Response from an XMLHttpRequest?

Retrieving XMLHttpRequest Response

XMLHttpRequest is a browser-based technology that allows you to make HTTP requests and asynchronously retrieve responses. Understanding how to access the response can be crucial for many web development tasks.

Getting the Response with XMLHttpRequest.responseText

When an XMLHttpRequest request is complete (i.e., XMLHttpRequest.readyState equals XMLHttpRequest.DONE), you can access the response's HTML content using XMLHttpRequest.responseText. This contains the HTML of the accessed site, as requested.

Example Usage:

To load and display an alert with the HTML from http://foo.com/bar.php, you can use the following code:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://foo.com/bar.php', true);
xhr.send(null);
Copy after login

Cross-Browser Compatibility

For enhanced cross-browser compatibility, consider using jQuery, which provides a cleaner and more concise way to make AJAX requests:

$.get('http://example.com', function(responseText) {
    alert(responseText);
});
Copy after login

Same Origin Policy

When not running on localhost, keep in mind the Same Origin Policy for JavaScript. To avoid cross-site requests, you may need to create a proxy script on your domain.

The above is the detailed content of How Do I Retrieve and Use the Response from an XMLHttpRequest?. 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