2011-01-21 66 views
1

如何在javascript中的相同視圖中加載html網址的內容。javascript html url loading問題

+1

請詳細得多的具體。 – polarblau 2011-01-21 10:18:16

+0

我正在解析一個xml文件,並且我正在討論的鏈接是解析完成後得到的內容。現在我想獲取該html鏈接的內容,以便在某些視圖上顯示該內容。 – neha 2011-01-21 11:01:06

+0

所有新手從哪裏來的? – BastiBen 2011-01-21 12:12:27

回答

1

另一種選擇是使用IFRAME標籤。

0

如果您正在討論使用Javascript加載另一個頁面的內容,您需要使用AJAX。

<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 older IE 
    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> 

更多信息和例子在W3Schools。 請注意,對於安全限制,AJAX不適用於不同的域。

+0

我正在Mac上使用Dashcode,因此在使用ActiveXObject時出現錯誤,對此的任何解決方案..... – neha 2011-01-24 06:58:06

0

的iFrame將是最好的選擇,你NEHA

<html> 
<head> 
</head> 

<body> 
<font face="verdana,arial" size="3"> 
<div align="center"> 
<p> 

<a href="http://www.altavista.com" target="iframe1">AltaVista.com</a> | 
<a href="http://www.aol.com" target="iframe1">AOL.com</a> | 
<a href="http://www.lycos.com" target="iframe1">Lycos.com</a> | 
<a href="http://www.yahoo.com" target="iframe1">Yahoo.com</a> 

<p> 
<iframe 
name="iframe1" 
width="600" 
height="400" 
src="http://www.stackoverflow.com" 
frameborder="yes" 
scrolling="yes"> 
</iframe> 
<p> 

</font> 
</div> 

<!-- 
name="iframe1" 
- Set all links to target the iframe1 name when you want the contents of the iframe to change from links on the originating page. 

width="600" - Width of the iframe 

height="400" - Height of the iframe * Width and height can be expressed in pixels or percent 

src="http://www.yahoo.com" - Initial page that will fill in the iframe 

frameborder="yes" - Border around the iframe is displayed by default 

scrolling="yes" - Allow scrollbars around the iframe for navigation Vaild values are yes, no and auto 

align="" - Valid entries are left and right left is set by default 
--> 

</body> 
</html> 
0

,如果你想輕鬆地做到這一點,沒有一個iframe,你可能會發現jQuery's load method有用

$('#id-of-element-that-accepts-html-result').load('/url-that-returns-html-snippet.xyz', { 
    //querystring parameters 
    foo: 'bar', 
    moo: 'par', 
});