我正在通过howcode关注youtube上的一系列教程。它是关于建立一个社交网络。当谈到喜欢/评论时,他使用api。但是,这对我不起作用,我想使用普通的ajax。我想提交一个类似的请求:
<form>
if (!DB::query('SELECT post_id FROM post_likes WHERE post_id=:postid AND user_id=:userid', array(':postid'=>$post['id'], ':userid'=>$userid))) {
echo "<input type='submit' name='like' value='Like' data-id=".$post['id'].">";
} else {
echo "<input type='submit' name='unlike' value='Unlike' data-id=".$post['id'].">";
}
echo "<span>".$post['likes']." likes</span>
</form>
达到这个ajax:
$('[data-id]').click(function() {
var buttonid = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "index.php?postid=" + $(this).attr('data-id'),
processData: false,
//ScontentType: "application/json",
data: '',
success: function(r) {
console.log("hhhhhhhhhhhhhhhh")
},
error: function(r) {
console.log(r)
}
});
});
然后去这里:
if (isset($_GET['postid'])) {
Post::likePost($_GET['postid'], $userid);
}
答案 0 :(得分:1)
您需要添加一个选择器,即类或ID。要在&amp;上使用jquery选择器的元素然后在该选择器上绑定事件。请检查以下代码更新。您还需要添加preventDefault
方法以防止该选择器的原始事件。
<form>
if (!DB::query('SELECT post_id FROM post_likes WHERE post_id=:postid AND user_id=:userid', array(':postid'=>$post['id'], ':userid'=>$userid))) {
echo "<input class = "submit-class" type='submit' name='like' value='Like' data-id=".$post['id'].">";
} else {
echo "<input class = "submit-class" type='submit' name='unlike' value='Unlike' data-id=".$post['id'].">";
}
echo "<span>".$post['likes']." likes</span>
</form>
AJAX
$('.submit-class').click(function(e) {
e.preventDefault();
var buttonid = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "index.php?postid=" + $(this).attr('data-id'),
processData: false,
//ScontentType: "application/json",
data: '',
success: function(r) {
console.log("hhhhhhhhhhhhhhhh")
},
error: function(r) {
console.log(r)
}
});
});