.post()请求的数值响应添加了0 [英] Numeric response from a .post() request is adding a 0
问题描述
我正在使用Wordpress ajax api通过.post()ajax将php函数的结果发送到客户端.问题是值返回0以及数字值.因此,如果数值为"3",我将得到"30".
I'm using the Wordpress ajax api to send the result of a php function to the client with .post() ajax. The problem is the value returning a 0 aswell as the numeric value. So if the numeric value is "3" I get "30".
因此,这里有一个php函数,可用来获取user_id并为该用户返回相应的看不见的注释计数.
So here I have a php function that I use to grab the user_id and return the corresponding unseen comment count for that user.
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".
If I place the word "test" after $count I'll get "3test0".
然后我使用间隔检查功能以查找新的看不见的注释.
I then use an interval to check function for new unseen comments.
$(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.我在这里缺少什么?
Now I use get_unseen_comment_count($user_id)
in another function to display the count in my template and it returns the correct value "3" so it's not doing anything extra that should be adding the 0. What am I missing here?
推荐答案
您必须在echo
语句后写exit;
.
如果请求URL为AJAX请求失败, wp-admin/admin-ajax.php,它将返回-1或0,具体取决于 失败的原因. 此外,如果AJAX请求成功,它也会 将返回0 .
If the AJAX request fails when the request url is wp-admin/admin-ajax.php, it will return either -1 or 0 depending on the reason it failed. Additionally, if an AJAX request succeeds, it will return a 0.
参考.
这篇关于.post()请求的数值响应添加了0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!