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
Release: 2024-11-28 08:39:11
Original
668 people have browsed it

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">alert(xhr.responseText);
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template