我有一个 html 链接,在这里(php 解释后):
<a href="javascript:void(0)" onclick="vote_comment(28, 1);" class="vote-arrow">
<img id="up-arrow-pic-comment-28" src="http://localhost/wordpress/wp-content/themes/backyard- cures/images/up_arrow_grey.png" alt="vote up" />
</a>
这是它调用的函数:
function vote_comment(comment_id, direction) {
$.post('http://localhost/wordpress/wp-content/themes/backyard-cures/backyard_funcs.php',
{voteType: direction, postId: comment_id, type: 'comment'},
'updateIcon(vote_count, direction, comment_id)',
'json');
}
这是 backyard_funcs.php:
if (isset($_POST['voteType'], $_POST['postId']) && is_user_logged_in()) {
if($_POST['type'] == 'comment') {
if (!get_user_meta(get_current_user_id(),'byc_comment_votes',true)) {
add_user_meta(get_current_user_id(),'byc_comment_votes',array($_POST['postId'] => $_POST['voteType']),true)
echo json_encode(array('vote_count' => $_POST['voteType'], 'direction' => $_POST['voteType'], 'comment_id' => $_POST['postId']));
}
else {
echo json_encode(array('vote_count' => $_POST['voteType'], 'direction' => $_POST['voteType'], 'comment_id' => $_POST['postId']));
//$old_vote=get_user_meta(get_current_user_id(),'byc_comment_votes['.$_POST[postId].']',true);
}
}
} else {
// bad request/hack attempt
echo 2;
}
我知道 updateIcon 函数(应该在成功后调用)没有被调用。我一直在使用chrome调试器。我知道执行进入 vote_comment 函数,然后执行就终止了(不知道为什么)。我没有收到任何控制台错误。
我意识到这个问题可能过于简单或不清楚。我提前道歉,我是新手(网络开发)。如果需要任何其他信息,请告诉我。提前致谢。
最佳答案
第三个参数应该是一个函数,而不是一个字符串。这是一个对代码进行最少更改的示例。
function vote_comment(comment_id, direction) {
$.post('http://localhost/wordpress/wp-content/themes/backyard-cures/backyard_funcs.php',
{voteType: direction, postId: comment_id, type: 'comment'},
function(data) { updateIcon(data.vote_count, data.direction, data.comment_id) },
'json'
);
}
编辑:向回调添加解析
编辑2:原来OP在使用chrome调试器时遇到了麻烦,我向他发送了这张图片以获取指导:/image/Y1uzh.png
查看ajax请求响应正文后,他能够自行调试问题,结果发现问题出在PHP中。
关于javascript - 实现 AJAX post 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25675450/