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

How Do I Retrieve and Display HTML Response Data from an XMLHttpRequest?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 08:39:11627browse

How Do I Retrieve and Display HTML Response Data from an XMLHttpRequest?

Retrieving Response Data from XMLHttpRequest

In web development, XMLHttpRequest allows for asynchronous data communication between a web page and a remote server. One common task is retrieving the HTML content of a remote URL into a JavaScript variable.

Getting the Response HTML

To access the HTML of the accessed site, use XMLHttpRequest.responseText within the XMLHttpRequest.onreadystatechange event handler. Here's an example:

<br>var xhr = new XMLHttpRequest();<br>xhr.onreadystatechange = function() {<br>  if (xhr.readyState === XMLHttpRequest.DONE) {</p>
<pre class="brush:php;toolbar:false">alert(xhr.responseText);

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

Cross-Browser Compatibility

For wider browser compatibility, consider using jQuery:

<br>$.get('http://foo.com/bar.php', function(responseText) {<br>  alert(responseText);<br>});<br>

Same-Origin Policy Considerations

Note that the Same-Origin Policy for JavaScript restricts access to data from a different origin unless additional measures are taken, such as creating a proxy script on your own domain.

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