我今天开始学习一些ajax技术,当我按下按钮时,我从另一个带有函数的文件中获取文本,但它们不起作用。
我的主文件
<html>
<head>
<script>
function showHint(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "request/testa.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button id="inp" style="background-color: #0000FF; color: #ffffff" onclick="showHint(this.value)">
Just do it!
</button>
<p><span id="txtHint"></span></p>
</html>
在向我发送文本的文件(request/testa.php)中是
test 2
<script>
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
</script>
并且 tekst 工作正常,我收到文本“test 2”和脚本,但不起作用。
最佳答案
使用innerHTML 将 javascript 代码写入页面将不会执行该脚本。
解决这个问题最简单的方法是使用 jQuery 的 load ,它将为您执行脚本。
关于javascript - 从另一个文件执行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36063690/