1

我正在使用 Wordpress ajax api 使用 .post() ajax 将 php 函数的结果发送到客户端。问题是返回 0 的值以及数值。所以如果数值是“3”我得到“30”。

所以在这里我有一个 php 函数,我用它来获取 user_id 并为该用户返回相应的看不见的评论计数。

 add_action("wp_ajax_return_unseen_comment_count","return_unseen_comment_count");
 function return_unseen_comment_count() {
    $user_id = $_POST['userId'];
    $count = get_unseen_comment_count($user_id);
    echo $count;
 }

如果我在 $count 后面加上“test”这个词,我会得到“3test0”。

然后我使用一个间隔来检查函数是否有新的看不见的评论。

$(document).ready(function() {
    var userId = fodAjax.user_id;
    var cmntCount = $(".cmnt-cnt").text();
    if (userId > 0) {
      setInterval(function() {
               data = {
                  action: 'return_unseen_comment_count',
                  userId: userId
               };
               $.post(ajaxurl, data, function (response) {  
                  console.log(response);                  
               });
      }, 10000); //10 seconds
    }
});

现在我get_unseen_comment_count($user_id)在另一个函数中使用在我的模板中显示计数,它返回正确的值“3”,所以它没有做任何额外的事情,应该添加 0。我在这里错过了什么?

4

1 回答 1

1

你必须写exit;echo声明之后。

如果请求 url 为 wp-admin/admin-ajax.php 时 AJAX 请求失败,它将根据失败的原因返回 -1 或 0。此外,如果 AJAX 请求成功,它将返回 0

参考

于 2013-01-16T11:59:15.333 回答