Getting the Response of XMLHttpRequest
XMLHttpRequest is a versatile tool for loading remote content into a JavaScript variable. To retrieve the HTML content of a specific URL, follow these steps:
Problem Statement:
How do you store the HTML of a remote site in a JS variable using XMLHttpRequest?
Solution:
XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange, triggered when XMLHttpRequest.readyState equalsXMLHttpRequest.DONE, contains the HTML response.
Example:
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { alert(xhr.responseText); } } xhr.open('GET', 'http://example.com', true); xhr.send(null);
Cross-Browser Compatibility:
For enhanced cross-browser compatibility, you can leverage jQuery:
$.get('http://example.com', function(responseText) { alert(responseText); });
Same Origin Policy:
Note that the Same Origin Policy for JavaScript restricts cross-origin requests. Consider creating a proxy script on your domain to bypass this limitation.
The above is the detailed content of How Can I Use XMLHttpRequest to Get and Store Remote HTML in a JavaScript Variable?. For more information, please follow other related articles on the PHP Chinese website!