使用Javascript从另一个页面加载特定内容 index.html 函数loadPage(){ 变量xhttp,rtext,x; xhttp=newXMLHttpRequest(); xhttp.onreadystatechange=函数(){ 如果(xhttp.readyState==4&&xhttp.status==200){ rtext=xhttp.responseText; x=rtext.getElementById('bottom'); } document.getElementById(“firstdiv”).innerHTML=x; }; open(“GET”,“first.html”,true); xhttp.send(); } 家 first.html
内容1 内容2 我只需要使用javascript将first.html中的“bottom”div加载到我的索引页面,并且面临错误 getElementById('bottom')不是定义属性 如何继续?尝试使用“first.html”的内容,然后查询该文档中所需的元素使用Javascript从另一个页面加载特定内容 index.html 函数loadPage(){ 变量xhttp,rtext,x; xhttp=newXMLHttpRequest(); xhttp.onreadystatechange=函数(){ 如果(xhttp.readyState==4&&xhttp.status==200){ rtext=xhttp.responseText; x=rtext.getElementById('bottom'); } document.getElementById(“firstdiv”).innerHTML=x; }; open(“GET”,“first.html”,true); xhttp.send(); } 家 first.html,javascript,dom,Javascript,Dom,内容1 内容2 我只需要使用javascript将first.html中的“bottom”div加载到我的索引页面,并且面临错误 getElementById('bottom')不是定义属性 如何继续?尝试使用“first.html”的内容,然后查询该文档中所需的元素 index.html <script > function loadPage(){ var xhttp,rtext,x; xhttp=new XMLHttpRequest(); xhttp.
index.html
<script >
function loadPage(){
var xhttp,rtext,x;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if (xhttp.readyState == 4 && xhttp.status == 200) {
rtext=xhttp.responseText;
x = rtext.getElementById('bottom');
}
document.getElementById("firstdiv").innerHTML=x;
};
xhttp.open("GET","first.html",true);
xhttp.send();
}
</script>
<body>
<div onClick="loadPage();">Home</div>
<div id="firstdiv"></div>
</body>
first.html
<body>
<div id="bottom">
<p>content 1</p>
</div>
<div id="bottom1">
content 2
</div>
</body>
未测试,但这可能是一个开始。JavaScript只在当前页面的元素上运行。当代码执行时
var doc = document.implementation.createHTMLDocument("Doc Title");
doc.body.outerHTML = rtext;
var bottom = doc.getElementById('bottom');
它希望在index.html上找到“bottom”。当响应加载到x中时,x包含first.html的文本,但它不能被识别为html,并且不能被解释为html
我同意e-e的答案——这是一个起点
rtext=xhttp.responseText;
x = rtext.getElementById('bottom');