最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - javascript: how to fetch the content of a web page - Stack Overflow

programmeradmin1浏览0评论

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', '', false);
req.send(null);
if(req.status == 200)
  alert(req.responseText);

Is there a better method/code?

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?

Share Improve this question edited Mar 17, 2022 at 8:42 VLAZ 29k9 gold badges62 silver badges83 bronze badges asked Mar 14, 2011 at 14:05 tictic 4,18915 gold badges51 silver badges87 bronze badges 1
  • 2 en.wikipedia.org/wiki/Same_origin_policy – epascarello Commented Mar 14, 2011 at 14:25
Add a comment  | 

4 Answers 4

Reset to default 12

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

The above does not work, because Ajax requests cannot access files/pages on other domains, due to security concerns. Typically, you can make a script using [Insert Server Side Language here] to download the requested page. Then your javascript can make a request to this page.

There is also 'JSONP', but this is typically used on sites that provide specific JSONP access, which most random URL's do not.

For security reasons, you cannot use AJAX to send a request to a different domain.

If you really need to do this, you can try using jQuery and iFrames (read more at (read more http://softwareas.com/cross-domain-communication-with-iframes).

Also, you can try with Access-Control-Allow-Origin: http://yourdomain:1234/ in headers, google for Cross-Origin Resource Sharing. It's relativelly new though, not all browsers know about this. That also depends if you have the control of the other server headers generation and few other things.

发布评论

评论列表(0)

  1. 暂无评论