2011-06-16 20 views
12

我想通過使用帶有URL的xmlhttprequest來獲取html的源代碼。有沒有人可以幫助我呢?我是編程新手,我不太清楚如何在沒有jQuery的情況下做到這一點。提前致謝。使用JavaScript與網址獲取HTML代碼

+1

您可能需要查看相同原產地政策的問題......只需搜索一下就可以找到大量信息。 – 2011-06-16 16:44:36

+0

但有沒有其他的方式去關於這件事?像不使用xmlhttprequest?用JavaScript? – simplified 2011-06-16 16:47:32

+1

沒有。 xmlhttprequest和iframe是唯一的方法,並且都受同源策略的限制。如果你想解決這個問題,遠程服務器需要配合(通過作爲jsonp,或者在它所服務的數據上加上一個特殊的頭文件) – rob 2011-06-16 17:28:48

回答

15

使用jQuery:

$.ajax({ url: 'your-url', success: function(data) { alert(data); } }); 

這個數據是你的HTML。

沒有jQuery的(只是JS):

function makeHttpObject() { 
    try {return new XMLHttpRequest();} 
    catch (error) {} 
    try {return new ActiveXObject("Msxml2.XMLHTTP");} 
    catch (error) {} 
    try {return new ActiveXObject("Microsoft.XMLHTTP");} 
    catch (error) {} 

    throw new Error("Could not create HTTP request object."); 
} 
var request = makeHttpObject(); 
request.open("GET", "your_url", true); 
request.send(null); 
request.onreadystatechange = function() { 
    if (request.readyState == 4) 
    alert(request.responseText); 
}; 
+0

@Senad Meskin感謝您的回答,但是可以使用jQuery做到這一點?我想知道是否有其他方法可以做到這一點。 – simplified 2011-06-16 16:49:26

+0

@Senad Meskin謝謝。但是,我試圖將這個函數寫在一個空的HTML文件中,該文件只是將上面的代碼放在腳本標記中。看起來readystate是1,並沒有通過。你知道爲什麼嗎?我已經更改爲網址了。但它仍然不起作用。 – simplified 2011-06-16 17:50:45

+0

您的網址是否指向另一臺服務器,如果是這樣,則是安全問題。 – 2011-06-16 17:53:29

2

有關於如何阿賈克斯在這裏使用教程:http://www.w3schools.com/ajax/default.asp

這是該教程所採取的示例代碼:

<html> 
<head> 
<script type="text/javascript"> 
function loadXMLDoc() 
{ 
var xmlhttp; 
if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","ajax_info.txt",true); 
xmlhttp.send(); 
} 
</script> 
</head> 
<body> 

<div id="myDiv"><h2>Let AJAX change this text</h2></div> 
<button type="button" onclick="loadXMLDoc()">Change Content</button> 

</body> 
</html>