我正在实现一个用于添加/删除记录的表。数据是通过表单写入到表中,但是在窗口重载后才显示(我想实现不重载)。我阅读了有关 ajax 的信息,我尝试使用它,但添加到表中不起作用。
在表中,我从数据库中推断出价值。通过单击添加字段,将打开一个模式窗口并捕获数据
<table class="table" id="tableID">
<thead class="thead-light">
<tr>
<th scope="col">id <span class="active sortid">↓</span><span>↑</span></th>
<th scope="col">Name <span class="active sortname">↓</span><span>↑</span></th>
<th scope="col">Price <span class="active sortprice">↓</span><span>↑</span></th>
<th scope="col">Rating <span class="active sortrating">↓</span><span>↑</span></th>
</tr>
</thead>
<tbody>
<?php
$result = mysqli_query($link,"SELECT id,name,price,rating FROM product");
while($row = mysqli_fetch_array($result)) {
echo '<tr>
<th scope="row">'.$row['id'].'</th>
<td>'.$row['name'].'</td>
<td>'.$row['price'].'</td>
<td>'.$row['rating'].'</td>
<td><button type="button" id="'.$row['id'].'" class="btn btn-primary edit">edit field</button></td>
<td><button type="button" data_id="'.$row['id'].'" class="btn btn-danger delete">delete field</button></td>
</tr>';
}
?>
</tbody>
</table>
<button type="button" class="btn btn-primary bye">add field</button>
<div class="modal" id="window">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="b-popup" id="popup1" method="post" id="ajax_form" action="">
<div class="form-group">
<label for="name">name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter name">
<label for="price">price</label>
<input type="text" class="form-control" name="price" id="price" placeholder="Enter price">
<label for="rating">rating</label>
<input type="text" class="form-control" name="rating" id="rating" placeholder="Enter rating">
</div>
<button type="submit" class="btn btn-primary btn2" data-dismiss="modal" >Submit</button>
</form>
</div>
</div>
</div>
</div>
在这里它实现了 ajax 并将其传递给addfield.php以写入数据库
$(document).ready(function() {
$('#ajax_form').submit(function(event){
event.preventDefault(); //останавливаем стандартную отправку
var name = $("#name").val();
var price = $("#price").val();
var rating = $("#rating").val();
$.ajax({
type: "POST",
url: "add_field.php",
data: {"name": name, "price": price,"rating": rating},
cache: false,
success:
$('#tableID').append('<tr><td>price</td></tr><tr><td>".$name."</td></tr>');
}
});
});
});
addfield.php
<?php
include ("db.php");
$name = $_POST['name'];
$price = $_POST['price'];
$rating = $_POST['rating'];
$link = db_connect();
$result = mysqli_query($link,"INSERT INTO product (id,
name,
price,
rating)
VALUE (null,
'$name',
'$price',
'$rating')");
?>
从服务器返回 json
像这样的东西