gpt4 book ai didi

javascript - 为什么我的脚本不能处理 ajax 文档?

转载 作者:行者123 更新时间:2023-12-03 12:02:45 24 4
gpt4 key购买 nike

我的 js 代码无法处理 ajax 加载的文档。

下面是我的 html-js 结构。

  1. index.html
  2. abc.js 包含在 index.html 中
  3. index.html 内的fine.html(由ajax_abc.js 加载)

如果我定义了一些变量(请参阅fine.html中的元素),该变量将变为空。

例如,

index.html:

<script src="abc.js"></script>

abc.js:

ajax load document sententes;
var a = document.getElementById('asdf'); // asdf is located in fine.html

浏览器控制台:

a; // result: null

a = document.getElementById('asdf');
a; // result: not null

我认为这是因为加载 abc.js 时,fine.html 不存在。

这就是 abc.js 无法在fine.html(ajax 文档)上运行的原因。

我把abc.js放在fine.html的底部,但没有效果。

如何让我的脚本在 ajax 文档上运行?

abc.js 中的 ajax 代码:

var xhr;
xhr = new XMLHttpRequest();
function xhrDocOpen(doc){
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
document.getElementById('bodyFrame').innerHTML=xhr.responseText;
}
}
xhr.open('GET',doc,true);
xhr.send();
}
xhrDocOpen('introOrgan.html');

最佳答案

您需要为文档使用正确的范围

这一行:

var a = document.getElementById('asdf');

失败,因为document适用于index.html,而不是fine.html。

首先,您需要等待fine.html 加载。

试试这个,它会等到内容加载完毕后再将a分配给从fine.html注入(inject)的元素:

var a;
var xhr;
xhr = new XMLHttpRequest();
function xhrDocOpen(doc){
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
// load content from fine.html into DOM
document.getElementById('bodyFrame').innerHTML=xhr.responseText;

// search DOM after fine.html content loaded
a = document.getElementById('asdf');
}
}
xhr.open('GET',doc,true);
xhr.send();
}
xhrDocOpen('introOrgan.html');

关于javascript - 为什么我的脚本不能处理 ajax 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25338227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com