javascript: how to fetch the content of a web page

tic picture tic · Mar 14, 2011 · Viewed 29.2k times · Source

In JS is it possible to fetch the content of a web page assigning it to a variable? For example, why the following toy code does not work?

var req = new XMLHttpRequest();
req.open('GET', 'http://www.google.com', false);
req.send(null);
if(req.status == 200)
  alert(req.responseText);

Is there a better method/code?

Answer

gion_13 picture gion_13 · Mar 14, 2011

use a server-side proxy like a php-page that reads the desired page and then make ajax calls to that proxy through javascript :

var req = new XMLHttpRequest();

req.open('GET', 'proxy.php?url=http://www.google.com', false);
req.send(null);

if(req.status == 200) {
   alert(req.responseText);
}