【发布时间】:2020-07-16 05:04:20
【问题描述】:
假设我有一个带有导航栏的 ejs 文件,其中包含类的 a-tags。每当单击每个 a-tags 时,我都会向服务器发出 http 请求,该服务器使用 html 代码响应,然后我将其设置为 div 的 innerHTMl。我面临的问题是我不能不做任何查询选择器,不能获取元素,甚至不能在响应 HTML 代码的 html 元素上做一个事件监听器。有没有办法让它工作,因为我真的需要这些工作。
我使用的外部 javascript 文件如下:
var arr = this.id.split('-')
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.querySelector('#nav-' + arr[1] + "-" + arr[2]).innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "/basic" + arr[1] + "-" + arr[2], true);
xhttp.send();
})
【问题讨论】:
-
status 200 和 readyState 4?有错误吗?
-
是的,上面的代码可以工作,只是我不能对 innerHTML 或 div 中的元素执行任何查询选择器甚至侦听器。好像他们不在那里
-
xhttp 在那里不可用。这是因为函数的范围。使用硬编码字符串再试一次,看看是否有更新作为健全性检查。或使用
this.responseText -
更新部分起作用了,它实际上将所选div的innerHTML设置为请求的响应文本。
-
我从这里得到了例子w3schools.com/xml/xml_http.asp
标签: javascript html jquery django express