1. 程式人生 > >JS遠端獲取網頁原始碼例項

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; //設定回撥函式
http://www.unitymanual.com/forum36.html unity3d教程
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>