开发者

Stray character in Ajax response?

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(respon开发者_运维知识库se) {
              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!


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

function newspaper_getpost() {
    $d = array('foo' => 'bar', 'baz' => 'long');
    die(json_encode($d));
}
add_action('wp_ajax_newspaper_getpost', 'newspaper_getpost');


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜