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:
Create an XMLHttpRequest object:
var xhr = new XMLHttpRequest();
Define an event listener for the onreadystatechange event, which is triggered when the request's state changes.
xhr.onreadystatechange = function() { ... };
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); }
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!