我的主要文件
<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工作正常,我得到了文本“测试2”和脚本,但那不起作用。
答案 0 :(得分:1)
使用innerHTML将javascript代码写入您的页面将不会执行该脚本。
最简单的方法是使用jQuery的load,其中将为您执行脚本。
答案 1 :(得分:0)
你必须在testa.php中改变一些东西。将所有内容放入函数中或只删除脚本标记。
function MyScript(){
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
}
或
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
之后,您可以替换innerHTML
函数的showHint函数中的eval
。
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
代表
eval(xmlhttp.responseText);
但请记住,eval功能为错误或黑客打开了大门。