[英]delete row with ajax function and php
我有一個包含 mysql 數據的表,我添加了一個垃圾按鈕,我想在使用 ajax 函數單擊垃圾按鈕時刪除每一行,這是我的 html:
<table border="1">
<?php
$sql ="SELECT * FROM music";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_object($result)){
echo '<tr><td>'.$row->file_name.'</td><td>'.$row->composer.'</td><td>'.$row->lyric.'</td><td>'.$row->music_thumb.'</td><td>'.'
<a href="#" id="'.$row->msuic_id.'" class="trash" >
جذف کردن
</a>
'.'</td></tr>';
}
?>
</table>
和我的 ajax 函數在這里:
$(function(){
$('.trash').click(function(){
var del_id= $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type:'POST',
url:'delete.php',
data:del_id,
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
})
});
還有我的“delete.php”頁面:
<?php
include('../db_inc.php');
$music_number = "POST['del_id']";
echo '$music_number';
$qry = "DELETE FROM music WHERE msuic_id ='$music_number'";
$result=mysql_query($qry);
?>
我想我的問題是ajax函數; 謝謝
試試這個
$.ajax({
type:'POST',
url:'delete.php',
data:{del_id:del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
})
並且也改變
$music_number = "POST['del_id']";
到
$music_number = $_POST['del_id'];
你的ajax代碼應該是這樣的:
$(function(){
$(document).on('click','.trash',function(){
var del_id= $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type:'POST',
url:'delete.php',
data:{'del_id':del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
});
});
});
而 PHP 代碼應該是:
<?php
include('../db_inc.php');
$music_number = $_POST['del_id'];
//echo $music_number;
$qry = "DELETE FROM music WHERE msuic_id ='$music_number'";
$result=mysql_query($qry);
if(isset($result)) {
echo "YES";
} else {
echo "NO";
}
?>
除了上述答案之外,您還應該委托您的點擊處理程序以防止不必要的重復
$(document).on('click', '.trash', function() { ... });
試試這個:
$music_number = POST['del_id']; in delete.php
write ajax function like:
$.ajax({
type:'POST',
url:'delete.php',
data:del_id,
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
});
以下是你需要糾正的事情
在“delete.php”文件中$music_number = "POST['del_id']"; // to $music_number = $_POST['del_id'];
$music_number = "POST['del_id']"; // to $music_number = $_POST['del_id'];
此外,在 ajax 的成功回調中,您正在檢查響應中未發送到此文件中的任何位置的“YES”。
更改為您的 ajax 請求
data: {'del_id':del_id},
希望這會有所幫助。
將數據作為對象發送給您,而不僅僅是值
...
type:'POST',
url:'delete.php',
data:{'del_id':del_id}, //<----here
....
並將其作為 delete.php 中的 POST
$music_number = $_POST['del_id'];
更新
將此添加到您的 delete.php
<?php
include('../db_inc.php');
$music_number = $_POST['del_id'];
$qry = "DELETE FROM music WHERE msuic_id ='$music_number'";
$result=mysql_query($qry);
if($result) {
echo "Yes";
} else {
echo "No";
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.