[英]Converting a button that executes PHP to jQuery/Ajax
我正在尝试为我的梦幻足球联赛编写一个功能,允许玩家相互交易。 从功能上讲,一切正常,但正如我在 PHP 中编写的所有代码一样,我遇到了一个烦人的问题,即每次按下按钮时,页面都会有效地刷新两次。 我读过我可以用 jQuery 和 Ajax 解决这个问题,但遗憾的是我对这两个都没有任何经验。
下面是一小部分代码,允许登录用户撤回他们提出的交易报价:
echo "<input type='submit' id='btn-danger' name='withdraw".$trade_id."' value='Withdraw'>";
if($_POST && isset($_POST['withdraw'.$trade_id])) {
$withdraw = $link->prepare("DELETE FROM trade_id_offers_out WHERE trade_id_offer_id = ".$trade_id);
$withdraw->execute();
}
这会为他们发出的每个交易报价创建一个“撤回”按钮,并具有唯一的“撤回”名称以及该报价在 SQL 表中的任何编号。
正如我在功能上所说,它工作得非常好。 但它刷新了页面两次,我想知道如何获取这段代码并将其变成更实用的东西?
非常感谢您的宝贵时间。
首先,您应该确保在任何其他 jQuery 之前将 jQuery 包含在您的页面 html 中(那里有很多教程)。
其次,您需要给提交按钮一个 class 以便您可以使用 jQuery 选择器 select 它。 将按钮的 php 代码更改为:
echo "<input type='submit' id='btn-danger' class='withdrawTradeBtn' name='withdraw".$trade_id."' value='Withdraw'>";
最后,您将对 url 发出 ajax 发布请求(在这种情况下,与您的页面相同的 url)。 js 看起来像这样,需要放置在 html 正文标记的末尾之前或在所有按钮都呈现之后:
(注意:我尚未对此进行测试,但它应该与您所追求的非常接近)
<script>
//we need to wait for the page to be loaded in the users browser
$(document).ready(function(){
//we are selecting all the buttons with the class withdrawTradeBtn
//we are binding to the click event so whenever any of the buttons are pressed the code will be ran.
$('.withdrawTradeBtn').on('click', function(e){
//we need to prevent the button from actually reloading the page
e.preventDefault();
//now we need to make a ajax post request to the url
$.post(
'/your/url', //the url to make the post
{$(this).attr('name'):'Withdraw'}, //the submitted data
function(data, status, jqXHR) {// success callback
//here is were you would delete the button or whatever
}
);
});
});
</script>
您很可能希望从 html 中删除交易条目。 您可以在 ajax 帖子的成功回调中执行此操作。 我真的不能在这里添加任何东西,因为我不知道你的 html 结构是什么样的。
希望这会有所帮助,如果您需要更多帮助,请告诉我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.