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