我已经花了好几个小时让这个工作起来并没有动摇一个预算。
我尝试做的是点击按钮时发送网址,但不刷新网页
按钮的php代码:
echo '<a href="#" class="approve-button" id="'.$link_url[link_url].'">Send</a>';
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>
votehandler.php:
<?php
$data = $_POST['id'];
mysql_query("UPDATE `link` SET `up_vote` = up_vote +1 WHERE `link_url` = '$data'");
?>
我已经从votehandler.php中删除了所有错误检查,试图得到任何回复,但到目前为止还没有。
欢迎任何建议,试图了解jquery / ajax。
答案 0 :(得分:5)
您的代码有两个问题:
'a[class="approve-button"]'
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");
}
});
});
});