javascript:如何获取网页的内容 [英] javascript: how to fetch the content of a web page

查看:170
本文介绍了javascript:如何获取网页的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JS中,可以获取将其分配给变量的网页内容?
例如,为什么以下玩具代码不起作用?

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

有更好的方法/代码吗?

解决方案

使用服务器端代理,例如读取所需页面的php页面,然后通过javascript对该代理进行ajax调用:

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


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?

解决方案

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

这篇关于javascript:如何获取网页的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆