JS远程获取网页源代码实例


复制代码 代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>远程网页源代码读取</title>
<style type="text/css">
/* 页面字体样式 */
body, td, input, textarea {
font-family:Arial;
font-size:12px;
}
</style>
<script type="text/javascript">
//用于创建XMLHttpRequest对象
function createXmlHttp() {
//根据window.XMLHttpRequest对象是否存在使用不同的创建方式
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest(); //FireFox、Opera等浏览器支持的创建方式
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器支持的创建方式
}
}
//直接通过XMLHttpRequest对象获取远程网页源代码
function getSource() {
var url = document.getElementById("url").value; //获取目标地址信息
//地址为空时提示用户输入
if (url == "") {
alert("请输入网页地址。");
return;
}
document.getElementById("source").value = "正在加载……"; //提示正在加载
createXmlHttp(); //创建XMLHttpRequest对象
xmlHttp.onreadystatechange = writeSource; //设置回调函数
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
//将远程网页源代码写入页面文字区域
function writeSource() {
if (xmlHttp.readyState == 4) {
document.getElementById("source").value = xmlHttp.responseText;
}
}
</script>
</head>
<body>
<h1>远程网页源代码读取</h1>
<div>
地址:<input type="text" id="url">
<input type="button" onclick="getSource()" value="获取源码">
</div>
<textarea rows="10" cols="80" id="source"></textarea>
</body>
</html>


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3