[英]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.