我有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]);
}
?>
答案 0 :(得分:0)
容易,当您获取数据时,清空表然后将数据再次放入其中 这部分代码:
$.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 );
答案 1 :(得分:0)
请注意,id选择器是“#”而不是“ #id”。
请尝试:
var idForNewData = "#" + gotId;
如Ultrazz008所述,您只是试图将单元格(td)添加到表中。但是,该表包含行(tr),每行包含单元格(td)。
最好以字母开头的ID(请输入check here)。
BR