繁体   English   中英

当使用 ajax 从另一个页面加载 html 时,未定义 Function

[英]Function is not defined when the html is load from another page with ajax

我在一页中有一个表,我用 ajax 获取数据库的行,我有一个按钮,onclick 他做了一个 functionR 命名为 deleteRow(当单击时未定义但定义)。

我要显示表格的页面:

<table>
    <thead>
        <td>Id</td>
        <td>Nome</td>
        <td>email</td>
        <td>numero</td>
        <td>data</td>
        <td>hora</td>
    </thead>
    <tbody>
    </tbody>
</table>
<script>
    $(document).ready(function(){
        update();
        setInterval(function(){update()}, 10000);
        function update(){
            $.ajax({
                type: 'post',
                url: 'getReservas.php',
                success: function (response) {
                    $("table").children("tbody").html(response);
                }
            });
        }
        function deleteRow(elem){
            console.log("oi");
            var isto = elem;
            var id = isto.attr("id");
            $.ajax({
                type: "POST",
                url: "deleteReserva.php",
                data: id,
                success: function(data){
                    isto.remove();
                }
            });
        }
    });
</script>

getReservas.php

<?php
    include "conexaoBaseDados.php";
    $query = $mysqli->query("SELECT * FROM reservas");
    $dados = array();
    if($query->num_rows > 0){
        while($row = $query->fetch_assoc()){
            $dados[] = $row;
        }
        foreach($dados as $r){
            echo "<tr>";
            echo "<td onclick='deleteRow(this);' id=". $r["id"] .">" . $r['id'] . "</td>";
            echo "<td>" . $r['nomeCliente'] . "</td>";
            echo "<td>" . $r['emailCliente'] . "</td>";
            echo "<td>" . $r['numeroCliente'] . "</td>";
            echo "<td>" . $r['dataReserva'] . "</td>";
            echo "<td>" . $r['horaReserva'] . "</td>";
            echo "</tr>";
        }
    }
?>

deleteRow() function 是在ready回调中定义的,因此它只存在于该回调的 scope 中。

您需要将 deleteRow function 代码移动到外部 scope。

例如 -

<script>

    function deleteRow(elem){
        console.log("oi");
        var isto = elem;
        var id = isto.attr("id");
        $.ajax({
            type: "POST",
            url: "deleteReserva.php",
            data: id,
            success: function(data){
                isto.remove();
            }
        });
    }

    $(document).ready(function(){
        update();
        setInterval(function(){update()}, 10000);
        function update(){
            $.ajax({
                type: 'post',
                url: 'getReservas.php',
                success: function (response) {
                    $("table").children("tbody").html(response);
                }
            });
        }
    });
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM