这里是初级开发人员,使用wordpress作为平台来制作网站。我希望用户能够点击一个向上投票按钮和向上投票不刷新页面的帖子。我想我可能应该使用javascript来突出显示单击后的按钮,以及更改投票数。然而,我很难弄清楚如何在不刷新页面的情况下运行php脚本(更新数据库)。
提前谢谢你,
发布于 2014-09-03 09:15:07
示例upvote php for post将此代码添加到您的函数文件中...
add_action('wp_ajax_upvote', 'upvote');
add_action('wp_ajax_nopriv_upvote', 'upvote');
function upvote() {
$postid= $_POST['id'];
$direction = $_POST['direction'];
$votes= get_post_meta($postid, '_votes', true);
if($direction='down') {
$votes--;
} else {
$votes++;
}
update_post_meta($postid, '_votes', $votes);
echo $votes;
exit();
}与$_POST变量的任何表单提交一样,上面的代码也需要安全性。不要在你的代码中遗漏这些!!
jQuery代码
jQuery(document).ready(function($){
$('.arrow').click(function(){ //if your upvote has class arrow?
//you need someway of passing postid to here!
//if you want up / downvote -- logic needed here, if not remove direction from below!
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'upvote',
id: id,
direction: direction //remove if not needed
},
success: function (output) { //do something with returned data
console.log(output);
jQuery('#postupvote').text(output); //write to correct id - maybe use postid in the id of the vote count on the page e.g. id="vote23" jQuery('#vote'+postid)
}
});
});
})有关更多信息,请使用google wordpress ajax
https://stackoverflow.com/questions/25632741
复制相似问题