Search code examples
javascripthtmlxmlhttprequestresponsetext

javascript: how to fetch the content of a web page


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?


Solution

  • 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);
    }