php - ajax 代码中的 Javascript 使用

标签 php javascript ajax

我正在更新问题。为了简化情况,我将这个脚本放在 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>

并且有other.php文件和下面的脚本

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

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

最佳答案

更改代码,以便在 other.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");
            };
        }
    };

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

关于php - ajax 代码中的 Javascript 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11696289/

相关文章:

php - 如何在 Laravel 5.2 中使用project_id打印project_name

javascript - 如何允许对象从其类继承成员?

php - 拉维尔 5 : Fetch ajax data in route and pass to controller

php - 根据选择选项(AJAX?)自动更改 PHP 变量

php - 是否可以在 Silverstripe 模板变量上运行一个函数来格式化输出?

php - 获取 mysql 资源字符串的第一行?

php - 截断 MySQL 表但排除第一列

javascript - 这段 JavaScript 的语法错误在哪里?

javascript - 从数组 React 中过滤过期的卡片

javascript - '解析 JSON 时出现 SyntaxError : Unexpected end of input'. 错误?