我有一个带有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功能; 感谢
答案 0 :(得分:10)
试试这个
$.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'];
答案 1 :(得分:5)
你的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";
}
?>
答案 2 :(得分:4)
除上述答案外,您还应委托点击处理程序以防止不必要的重复
$(document).on('click', '.trash', function() { ... });
答案 3 :(得分:2)
将数据作为对象发送,而不仅仅是值
...
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";
}
?>
答案 4 :(得分:2)
试试这个:
$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")
}
}
})
});
答案 5 :(得分:2)
以下是您需要纠正的事项
在“delete.php”文件中
$music_number = "POST['del_id']";
// to
$music_number = $_POST['del_id'];
此外,在ajax的成功回调中,您正在检查“YES”作为响应,而不是在此文件中的任何位置发送。
更改为您的ajax请求
data: {'del_id':del_id},
希望这有帮助。