[英]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.