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

How Do I Retrieve Data from an XMLHttpRequest Response?

Patricia Arquette
Release: 2024-12-03 12:25:13
Original
436 people have browsed it

How Do I Retrieve Data from an XMLHttpRequest Response?

How to Retrieve XMLHttpRequest Response Data

XMLHttpRequest provides a way to load and manipulate data from remote URLs through JavaScript. With it, you can obtain the HTML content of a website and store it in a variable for further processing.

To achieve this, execute the following steps:

  1. Create an XMLHttpRequest object:

    var xhr = new XMLHttpRequest();
    Copy after login
  2. Define an event listener for the onreadystatechange event, which is triggered when the request's state changes.

    xhr.onreadystatechange = function() { ... };
    Copy after login
  3. Within the event listener, check if the request has completed (XMLHttpRequest.DONE) and retrieve the response text using xhr.responseText.

    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
    }
    Copy after login
  4. Send an HTTP GET request to the desired URL:

    xhr.open('GET', 'http://foo.com/bar.php', true);
    xhr.send(null);
    Copy after login

Note that cross-browser compatibility can be enhanced by using a library like jQuery, which simplifies the process and accounts for browser-specific issues:

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

Keep in mind the Same Origin Policy for JavaScript, which restricts cross-origin requests. Consider using a proxy script to overcome this limitation.

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