ajax代码期间使用Javascript

Javascript usage during ajax code

本文关键字:Javascript 代码 ajax      更新时间:2024-03-20

我再次提出问题。为了简化情况,我在index.php文件中有这个脚本

<form name="f" action="index.php" method="post">
    <input type="button" name="but" id="but" value="Retrieve">
    <div id="div"></div>
    <input type="submit" name="ok">
</form>

<script type="text/javascript">
document.getElementById("but").onclick = function(){
    var http = false;
    if (window.XMLHttpRequest){
        http = new XMLHttpRequest();
    } else {
        http = new ActiveXObject("Microsoft.XMLHttp");
    }
    if (http){
        http.open("POST","other.php",true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.onreadystatechange = function(){
            if (http.status==200 && http.readyState==4){
                document.getElementById("div").innerHTML = http.responseText;
            }
        };
        http.send(null);
    }
};
document.getElementById("y").onclick = function(){
    alert("okaaay");
};
</script>

并具有其他.php文件和下面的脚本

<?php
echo "<input type='text' name='y' id='y'>";
?>

Ajax脚本运行得很好,但我的问题是,当这个标记的输入元素在index.php页面中检索时,使用第二个JavaScript代码我无法操作它,请帮忙,谢谢:)

更改代码,以便在其他php的响应返回后设置"y"onclick,如下所示:

 http.onreadystatechange = function(){
        if (http.status==200 && http.readyState==4){
            document.getElementById("div").innerHTML = http.responseText;
            document.getElementById("y").onclick = function(){
              alert("okaaay");
            };
        }
    };

否则,您将在一个尚不存在的元素上设置该事件处理程序:-)

我认为您应该只发回一些信息:

$response = json_encode( array('type'=>'text','name'=>'y','id'=>'y') );
print $response;

然后,当您收到它(作为application/json类型)时,使用javascript创建一个input类型的新元素,然后使用您收到的json为它提供您想要的属性。创建并存储在变量中后,将该元素放在div中。