Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从另一个文件执行脚本_Javascript_Php_Ajax - Fatal编程技术网

Javascript 从另一个文件执行脚本

Javascript 从另一个文件执行脚本,javascript,php,ajax,Javascript,Php,Ajax,我今天开始学习一些ajax技术,当我按下按钮时,我会从另一个文件中获取文本,但它们不起作用 我的主文件 <html> <head> <script> function showHint(str) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() {

我今天开始学习一些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>

函数showHint(str){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;
}
};
open(“GET”、“request/testa.php?q=“+str,true”);
xmlhttp.send();
}
想做就做

在发送给我文本的文件(request/testa.php)中

测试2
document.getElementById(“inp”).value=“你做到了!”;
document.getElementById(“inp”).style.backgroundColor=“ffffff”;

tekst工作正常,我得到了文本“test2”和脚本,但这不起作用。

使用innerHTML将javascript代码写入页面不会执行脚本


最简单的方法是使用jQuery,它将为您执行脚本。

您必须在testa.php中更改某些内容。将所有内容放在函数中,或者删除脚本标记

    function MyScript(){
        document.getElementById("inp").value="You did it!";
        document.getElementById("inp").style.backgroundColor="ffffff";
    }

之后,您可以将showHint函数中的
innerHTML
替换为
eval
函数

   document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
为了


但是请记住,eval函数为bug或黑客打开了大门。

这里没有jQuery。当我没有jQuery或不想使用它时,我该怎么办?将要执行的代码移动到
onreadystatechange
函数中。否则,您将需要添加一些hack来从加载的文件中拉出脚本页面并执行。
    document.getElementById("inp").value="You did it!";
    document.getElementById("inp").style.backgroundColor="ffffff";
   document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
    eval(xmlhttp.responseText);