Php Ajax/jquery如何从按钮单击发送数据而不刷新页面
我已经试了好几个小时想让它发挥作用,但一点也没动 我想做的是在点击按钮时发送一个url,但不刷新页面 按钮的php代码:Php Ajax/jquery如何从按钮单击发送数据而不刷新页面,php,jquery,mysql,ajax,Php,Jquery,Mysql,Ajax,我已经试了好几个小时想让它发挥作用,但一点也没动 我想做的是在点击按钮时发送一个url,但不刷新页面 按钮的php代码: echo '<a href="#" class="approve-button" id="'.$link_url[link_url].'">Send</a>'; echo'; jquery代码: <script type="text/javascript"> //Attach an onclick handler to eac
echo '<a href="#" class="approve-button" id="'.$link_url[link_url].'">Send</a>';
echo';
jquery代码:
<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>
//将onclick处理程序附加到每个用于“批准”的按钮
$(“批准按钮”)。单击(函数(){
//获取单击的按钮的ID
要批准的项目的变量id=$(this.attr(“id”);
$.ajax({
url:“votehandler.php”//这是处理SQL插入的页面
类型:“POST”,
数据:“id=“+id\u of_item\u to_approve,//您发送到some-page.php的数据
成功:函数(){
log(“AJAX请求成功”);
},
错误:函数(){
log(“AJAX请求失败”);
}
});
});
votehandler.php:
<?php
$data = $_POST['id'];
mysql_query("UPDATE `link` SET `up_vote` = up_vote +1 WHERE `link_url` = '$data'");
?>
您的代码有两个问题:
- jquery选择器不工作。正确的是:
'a[class=“approve button”]”
- 代码应该包装在jquery函数中,以确保在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");
}
});
});
});
您的代码有两个问题:
- jquery选择器不工作。正确的是:
'a[class=“approve button”]”
- 代码应该包装在jquery函数中,以确保在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");
}
});
});
});