Ajax 响应中的流浪角色?
我正在使用 wordpress。我使用 jQuery 进行 ajax 调用,PHP 回显出一个 JSON 对象,但是我在 javascript 中得到的响应在末尾添加了一个“0”,这使得解码 json 对象失败。
PHP:
function newspaper_getpost() {
$d = array('foo' => 'bar', 'baz' => 'long');
echo json_encode($d);
}
add_action('wp_ajax_newspaper_getpost', 'newspaper_getpost');
JS:
$.post(MyAjax.ajaxurl,{
action : 'newspaper_getpost',
postID : $(this).val()
}, function(response) {
console.log(response);
});
输出:
{"foo":"bar","baz":"long"}0
我尝试过
echo substr( json_encode($d), 0, -1);
,
{"foo":"bar","baz":"long"0
所以我确定它不是 PHP 端。我可以把“0”从响应的末尾去掉,但我觉得有更大的事情正在发生,我不想做一个廉价的黑客让它工作。顺便说一句,JQuery 1.6.1。谢谢!
I'm using wordpress. I make a ajax call with jQuery, PHP echos out a JSON object, but the response I get in javascript has a "0" added to the end which makes decoding the json object fail.
PHP:
function newspaper_getpost() {
$d = array('foo' => 'bar', 'baz' => 'long');
echo json_encode($d);
}
add_action('wp_ajax_newspaper_getpost', 'newspaper_getpost');
JS:
$.post(MyAjax.ajaxurl,{
action : 'newspaper_getpost',
postID : $(this).val()
}, function(response) {
console.log(response);
});
Output:
{"foo":"bar","baz":"long"}0
I tried
echo substr( json_encode($d), 0, -1);
and got
{"foo":"bar","baz":"long"0
so I'm sure its not the PHP side. I could just drop the "0" off the end of the response, but I feel like something bigger is going on nd I don't want to do a cheap hack to make it work. JQuery 1.6.1 btw. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
很明显有一个 0 与这段 javascript 完全无关。您可以看到您删除了响应中的最后一个字符,并删除了
}
但 0 仍然存在。您需要查看 PHP/HTML 的其余部分,因为正在输出的某个地方有一个杂散字符。如果你要添加 exit();回声之后,您会看到 0 消失。
It's obvious there is a 0 completely unrelated to this javascript piece. You can see that you chopped the last character off of the response and it removed the
}
but the 0 remains. You need to look at the rest of your PHP/HTML as there is a stray character somewhere being output.If you were to add exit(); right after the echo, you'd see the 0 go away.
试试这个
Try this
这意味着在您的
add_action('wp_ajax_newspaper_getpost', 'newspaper_getpost');
php 代码之后/内部有一些回声。寻找 print_r()、echo 或类似的东西。That means there is something echoing after/inside your
add_action('wp_ajax_newspaper_getpost', 'newspaper_getpost');
php code. Look for a print_r(), echo, or something similar.