以下代码是我目前用来尝试将帖子ID提供给vote.php,但是这当前返回[object Object]。如果点击链接,我怎么能传递正确的ID?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$.ajax({
type: "POST",
data: "id=" + $(this).attr("href", "id"),
url: "vote.php"
});
</script>
<a href="javascript:;" id="1"><div id="button">Like!</div></a>
<a href="javascript:;" id="2"><div id="button">Like!</div></a>
<a href="javascript:;" id="3"><div id="button">Like!</div></a>
谢谢!
答案 0 :(得分:3)
您需要将ajax调用绑定到单击处理程序:
$(document).on("click","a",function(e){
$.ajax({
type: "POST",
data: "id=" + $(this).attr("id"),
url: "vote.php"
});
});
答案 1 :(得分:1)
您应该考虑将其更改为:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function vote(_obj) {
$.ajax({
type: "POST",
data: "id=" + $(_obj).attr("href", "id"),
url: "vote.php"
});
}
$(document).ready(function() {
$('.vote').click(function() {
vote(this);
return false;
});
});
</script>
<a id="1" class="vote"><div>Like!</div></a>
<a id="2" class="vote"><div>Like!</div></a>
<a id="3" class="vote"><div>Like!</div></a>
一些注意事项:
答案 2 :(得分:0)
在您的代码中,您将链接的href分配给"id"
,这没有多大意义......您应该使用事件处理程序进行点击...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('a.likeBTN').click($.ajax({
type: "POST",
data: "id=" + $(this).attr("id"),
url: "vote.php"
}))});
</script>
<a href="javascript:;" class="likeBTN" id="1"><div id="button">Like!</div></a>
<a href="javascript:;" class="likeBTN" id="2"><div id="button">Like!</div></a>
<a href="javascript:;" class="likeBTN" id="3"><div id="button">Like!</div></a>