尝试构建一个简单的jQuery,该jQuery允许用户单击表行中的按钮,该按钮应运行单独的PHP脚本,以便在一个操作中从数据库行中删除项目并删除表行。(一旦工作,将迁移到准备好的语句。)
HTML
<tr id="wish_list_row2">
<td class="text-center">
<a href="#" data-toggle="tooltip" data-placement="bottom" title="Click to download this Resource" style="margin-right:15px;"><i class="fa fa-download"></i></a>
<a onclick="deleteWishList(3,1)" data-toggle="tooltip" data-placement="bottom" title="Click to remove this Resource from your Wish List"><i class="fa fa-gift"></i></a>
</td>
</tr>
<tr id="wish_list_row3">
<td class="text-center">
<a href="#" data-toggle="tooltip" data-placement="bottom" title="Click to download this Resource" style="margin-right:15px;"><i class="fa fa-download"></i></a>
<a onclick="deleteWishList(4,1)" data-toggle="tooltip" data-placement="bottom" title="Click to remove this Resource from your Wish List"><i class="fa fa-gift"></i></a>
</td>
</tr>
JS-
function deleteLike(rid,uid) {
$.post("remove_this_item.php?rid="+rid+"&uid="+uid);
$('#row'+rid).remove();
return false;
}
PHP
include_once ('[INCLUDE MYSQL CONNECTION VARIABLES - removed for this demo]');
$rid = $_GET['rid'];
$uid = $_GET['uid'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// delete this 'like' from the db for this user
$sql = "DELETE FROM likes WHERE user_id_REF='$uid' AND resource_id_REF='$rid' LIMIT 1";
$conn->query($sql);
mysqli_close($conn);
当我单击"删除"链接时,tr会按预期删除。但是,数据库行保持不变。如果我在url中手动设置PHP页面上的rid和uid,那么db行将被删除。我尝试过修改一些东西(比如rid和uid顺序),但还没有成功。
我对JS还不是很熟悉,所以也许我在编写函数时搞砸了?
您正在执行$.post
,但在php脚本中,您正在尝试检索$_GET[]
。将其更改为$_POST[]
,它应该可以正常工作。
$.post()
是使用HTML method="POST"
的快捷方式,因此您需要将参数作为表单数据传递,而不是在查询字符串中传递:
$.post( "remove_this_item.php", { rid: rid, uid: uid } );
如果要在查询字符串中传递参数,请使用$.get()
:
$.get("remove_this_item.php?rid="+rid+"&uid="+uid);