views:

65

answers:

2

I'd like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.

Say, if I wanted to load and alert() the HTML of http://foo.com/bar.php, how would I do that?

+1  A: 

You can get it by XMLHttpRequest.responseText.

Here's a Firefox compatible example.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);

For better crossbrowser compatibility and less verbosity with firing ajaxical requests I'd suggest jQuery.

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

Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.

BalusC
Thanks, it worked :-)
Rohan
You're welcome :) Don't forget to mark the answer accepted. Also see http://stackoverflow.com/faq
BalusC
A: 

Try to look up some XMLHttpRequests tutorials in Google, like this one:

http://www.cristiandarie.ro/asp-ajax/Async.html

There are tons of resources available on the topic.

You should also look into JS libraries like jQuery or prototype. They will really make your JavaScript life easier.

Ivar Bonsaksen