gpt4 book ai didi

php - Ajax/jquery 如何在不刷新页面的情况下从按钮单击发送数据

转载 作者:行者123 更新时间:2023-11-29 04:23:42 24 4
gpt4 key购买 nike

我已经尝试了几个小时来让它工作,但没有动一动。

我想做的是在单击按钮时发送一个 url,但不刷新页面

按钮的php代码:

    echo '<a href="#" class="approve-button" id="'.$link_url[link_url].'">Send</a>';

j查询代码:

<script type="text/javascript">

//Attach an onclick handler to each of your buttons that are meant to "approve"
$('approve-button').click(function(){

//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");


$.ajax({
url: "votehandler.php", //This is the page where you will handle your SQL insert
type: "POST",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});

});

</script>

投票处理程序.php:

<?php

$data = $_POST['id'];
mysql_query("UPDATE `link` SET `up_vote` = up_vote +1 WHERE `link_url` = '$data'");

?>

我从 votethandler.php 中删除了所有错误检查以尝试获得任何响应,但到目前为止一无所获。

欢迎任何建议,试图理解 jquery/ajax。

最佳答案

您的代码有两个问题:

  • jquery 选择器不工作。正确的是:'a[class="approve-button"]'
  • 代码应包含在 jquery ready() 中函数以确保在 javascript 代码执行之前已经加载了 DOM(带有链接)。

这是一个工作示例:

$(function() { // wrap inside the jquery ready() function

//Attach an onclick handler to each of your buttons that are meant to "approve"
$('a[class="approve-button"]').click(function(){

//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");


$.ajax({
url: "votehandler.php", //This is the page where you will handle your SQL insert
type: "POST",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});

});

});

关于php - Ajax/jquery 如何在不刷新页面的情况下从按钮单击发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16431713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com