为什么我的脚本不工作在ajax文档

why my script is not working on ajax document?

本文关键字:ajax 文档 工作 我的 脚本 为什么      更新时间:2023-09-26

我的js代码不能在ajax加载的文档上工作。

下面是我的html-js结构。

  1. index . html
  2. abc.js包含在index.html
  3. fine.html inside index.html(加载ajax_abc.js)

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

例如,

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');

您需要为document使用正确的作用域。

这一行:

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

是失败的,因为document是index.html,而不是fine.html。

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

试试这个,它等待直到内容被加载,然后才将a分配给从fine.html中注入的元素:

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');