[英]How to update table without adding new table on each button click?
單擊按鈕時,我有 3 個文件用於顯示數據。 當我每次單擊按鈕時,如何不繼續添加表格? 每次單擊按鈕時,我都希望獲得刷新的數據。
如果按鈕 id 和數據 id 相等,我曾嘗試刪除,但沒有奏效。 有沒有簡單的做法?
基於 HTML 的 PHP
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>MINI TEST</title>
</head>
<style>
.oldList td{
border: 1px solid gray;
background: lightblue;
}
.oldList{
width: 100px;
margin: 50px;
}
.showNewData td{
border: 1px solid gray;
background: lightgreen;
}
.showNewData{
width: 100px;
margin: 50px;
}
</style>
<body>
<?php
$oldList[] = array('1' => '1', '2' => 'mango','3' => '340');
$oldList[] = array('1' => '2', '2' => 'peach', '3' => '480');
foreach ($oldList as $value){
$idForList = $value['1'];
print "<table class='oldList'>";
print "<tr><td>".$value['1']."</td><td>".$value['2']."</td><td>".$value['3']."</td></tr>";
print "</table>";
print"<button class='newData' data-name='$idForList' id='$idForList'>{$idForList}NEW DATA</button>";
$idForNewData = "id" . strval($idForList);
print "<table class='showNewData' id='$idForNewData'></table>";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="mini_test_ajax.js"></script>
</body>
</html>
JS
$(document).ready(function(){
$('.newData').click(function(){
var gotId = $(this).data('name');
var idForNewData = "#id" + gotId;
$.ajax({
url: "mini_test_sql.php",
type: "POST",
data: {
"gotId": $(this).data("name")
},
success: function(data) {
console.log("success");
$.each(JSON.parse(data), function(key, value){
$(idForNewData).append("<td>" + value + "<td>");
});
},
error: function(xhr,XMLHttpRequest,errorThrown){
console.log("Fail");
console.log("xhr: " + xhr);
console.log("XMLHttpRequest: " + XMLHttpRequest);
console.log("errorThrown: " + errorThrown);
}
});
});
});
PHP
<?php
$idForList = $_POST['gotId'];
$productList[] = array();
$productList[0] = array(
'id' => "1",
'name' => "mango 2 ",
'price' => "280"
);
$productList[1] = array(
'id' => "2",
'name' => "peach 2",
'price' => "300"
);
if($idForList == 1){
echo json_encode($productList[0]);
}
if($idForList ==2){
echo json_encode($productList[1]);
}
?>
很簡單,當你拿到數據的時候,清空表然后再把你的數據放進去這部分代碼:
$.each(JSON.parse(data), function(key, value){
$(idForNewData).append("<td>" + value + "<td>");
});
應該是這樣的:
$(idForNewData).html("");
var d = "<tr>";
$.each(JSON.parse(data), function(key, value){
d += "<td>" + value + "<td>";
});
d += "</tr>";
$(idForNewData).html( d );
注意 id 選擇器是 '#' 而不是 '#id'。
請嘗試:
var idForNewData = "#" + gotId;
正如 Ultrazz008 所提到的,您只是想將單元格 (td) 添加到表格中。 但是,表格包含行 (tr),任一行包含單元格 (td)。
ID 最好以字母開頭(請在此處查看)。
BR
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.