【发布时间】:2021-07-18 20:23:08
【问题描述】:
我正在尝试将外部脚本导入 HTML 文件的标题。脚本的名称应从定期更新的 SQL 数据表中获取(因此,将导入不同的脚本)。为此,我设置了一个 XMLHttpRequest,在函数中我将 js = 设置为从 SQL 数据表中获取的文本,最后,我将新的 js 附加到我的标题顶部。我认为这可以解决问题,但是,脚本似乎没有成功导入。例如,如果我从适当的脚本控制台记录变量“cond”,那么我会得到一个错误。所以我的问题是为什么脚本没有被执行,我该怎么做才能修复它?
script3.js
var cond = "hallo"
index.html
<script src="script1.js"></script>
<script src="script2.js"></script>
<script> //import script with name taken from SQL database
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); // New request object.
oReq.onload = function() {
const js = document.createElement("script");
var noQuotes = this.responseText.split('"').join('');
js.src = noQuotes;
document.head.appendChild(js); //script should now have been appended to top of head
};
oReq.open("get", "index.php", true);
oReq.send();
</script>
<script>
console.log(cond). //attept to console log variable from imported js file
</script>
【问题讨论】:
-
..然后我得到一个错误...什么错误?
-
您附加的
<script>在另一个<script>中 -
什么是
this.responseText? -
我得到的错误:“Uncaught ReferenceError: cond is not defined”
-
this.responseText 是从 SQL 表中获取的单元格内容
标签: javascript html sql ajax