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
Patricia ArquetteOriginal
2024-12-03 12:25:13509browse

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();
  2. Define an event listener for the onreadystatechange event, which is triggered when the request's state changes.

    xhr.onreadystatechange = function() { ... };
  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);
    }
  4. Send an HTTP GET request to the desired URL:

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

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);
});

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!

Statement:
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