到目前为止我尝试过的事情: 当我使用Javascript将id添加到数据参数时,该行不会被删除。当我用php echo $ id添加id时,它会删除错误的行。 如何正确地为我要删除的行的ajax数据添加id?
我的代码
(省略了dbconnect代码)
$sql = "SELECT id, product_id, price, quantity FROM tbl_cart WHERE member_id = '$member_id' ";
$result = $conn->query($sql);
echo "<table class='anyClass'>";
echo "<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Remove</th>
<th>Add</th>
</tr>";
while($row = $result->fetch_assoc()) {
$id = $row['id'];
echo "<tr>
<td>".$row['id']."</td>
<td>".$row['product_id']."</td>
<td>".'$'.$row['price']."</td>
<td>".$row['quantity']."</td>
<td><span class='delete' id='<?php echo $id; ?>'>Delete</span>
</td>
</tr>";
}
echo "</table>";
$conn->close()]
?>
我的AJAX / JQUERY脚本
<script>
$(document).ready(function(){
// Delete
$('.delete').click(function(){
var el = this;
var id = this.id;
/* This code doesn't seem to work. Not sure why the author used split()
var splitid = id.split("_");
// Delete id
var deleteid = splitid[0];
*/
// AJAX Request
$.ajax({
url: 'remove.php',
type: 'POST',
data: { id:8},
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(800, function(){
$(this).remove();
});
}
});
});
});
</script>
答案 0 :(得分:0)
首先你在这里做错了。
data: { id:8}
由于要删除的ID是硬编码的,因此将始终删除相同的ID。
对我而言,这里最好的事情就是这样。
echo "<tr>
<td>".$row['id']."</td>
<td>".$row['product_id']."</td>
<td>".'$'.$row['price']."</td>
<td>".$row['quantity']."</td>
<td><span class='delete' data-id=".$id.">Delete</span></td>
</tr>";
在这种方法中,我将使用.data jQuery
<script>
$(document).ready(function(){
// Delete
$('.delete').click(function(){
var el = this;
var id = $(el).data('id');
// AJAX Request
$.ajax({
url: 'remove.php',
type: 'POST',
data: { id: id },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(800, function(){
$(this).remove();
});
}
});
});
});
</script>
因此,在脚本js / jQuery中,我们将从span元素中获取属性data-id的值,现在它将动态获取行的id。
答案 1 :(得分:0)
我在代码中发现了错误。它在这里:
<td><span class='delete' id='<?php echo $id; ?>'>Delete</span>
因为我已经在php中所有我必须做的就是改变它:
<td><span class='delete' id= $id >Delete</span>
它开始在mysql中删除我的行。