Home > Web Front-end > JS Tutorial > How Can I Use XMLHttpRequest to Get and Store Remote HTML in a JavaScript Variable?

How Can I Use XMLHttpRequest to Get and Store Remote HTML in a JavaScript Variable?

Barbara Streisand
Release: 2024-11-22 13:32:12
Original
328 people have browsed it

How Can I Use XMLHttpRequest to Get and Store Remote HTML in a JavaScript Variable?

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);
Copy after login

Cross-Browser Compatibility:

For enhanced cross-browser compatibility, you can leverage jQuery:

$.get('http://example.com', function(responseText) {
    alert(responseText);
});
Copy after login

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!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template