实际上我正在研究ajax,我想将iframe转换为div 意味着iframe的功能是什么,我想在div中使用相同的内容
感谢。
答案 0 :(得分:7)
您不能在简单的div中拥有完全相同的iframe功能。这就是为什么他们有两个不同的名字。 iframe有点沙盒,可以在任何域上打开网址。
在当今的浏览器中使用 Ajax ,您必须坚持使用同源策略,这意味着您只能从您的网站所在的同一域中加载内容。
所以,除了这个限制以及在这里无法在div中模仿iframe的沙盒这一事实是一个带有javascript的简单的ajax 解决方案,你可以用于实现网站导航,例如:
<强> HTML 强>
<ul id="nav">
<li><a href="page1.html">page1</a></li>
<li><a href="page2.html">page2</a></li>
<li><a href="page3.html">page3</a></li>
</ul>
<强>的Javascript 强>
// select the menu element
var nav = document.getElementById("nav");
// watch for clicks on the menu
nav.onclick = function(e) {
// get the element that was clicked
e = e || window.event;
var el = e.target || e.srcElement;
// only act if it was a link
if (el.nodeName == "A") {
// making a call is as simple as this
ajax(el.href, function(data) {
// do something with the server's response
// e.g.: put it to the #content element
document.getElementById("content").innerHTML = data;
});
// prevent default action
return false;
}
};
///////////////////////////////////////////////////////////////////////////////
function getXmlHttpObject() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function ajax(url, onSuccess, onError) {
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function () {
if (this.readyState == 4) {
// onError
if (this.status != 200) {
if (typeof onError == 'function') {
onError(this.responseText);
}
}
// onSuccess
else if (typeof onSuccess == 'function') {
onSuccess(this.responseText);
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}
答案 1 :(得分:2)
@rajesh,您无法通过Ajax加载外部网页,除非您在网站上放置一个带有Ajax调用的JavaScript文件,其中包含您希望在Div中放置在您网站上的内容。因此,唯一的方法是使用Iframe。