您不能在简单的div中拥有iframe的完全相同的功能。这就是为什么他们有两个不同的名字。 iframe有点沙盒,可以在任何域上打开网址。
在当今的浏览器上使用Ajax,您必须坚持使用同源策略,这意味着您只能从您的站点运行的同一域中加载内容。
所以,除了这个限制以及这里无法在div中模拟iframe之类沙盒的事实,这是一个简单的javascript ajax解决方案,您可以使用它来实现网站导航:
HTML
使用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;
}