游.程 2016-07-20 13:48 采纳率: 0%
浏览 24

为什么wp_send_json返回null

Objective: make the button "Add to favorites" and the page with the map of selected goods. My favorites post id stored in js-cookie array

liked = $.cookie("liked");
$.ajax({
    type: "GET",
    url: ajaxurl,
    data: {
        action : 'ids',
        id : liked
    },
    success: function (response) {
    console.log('AJAX response : ',response);
}

in functions.php

add_action( 'wp_ajax_ids', 'ids_function' );
add_action( 'wp_ajax_nopriv_ids', 'ids_function' );    

function ids_function() 
{
    $myArray = array($_REQUEST['id']); 
    wp_send_json( $myArray );

}

in the page with the map of selected goods i call finction ids_function() and page return null. But in console.log i see the need array. How to get it in my page?? TNX!

  • 写回答

1条回答 默认 最新

  • weixin_33695082 2016-07-20 14:46
    关注

    Not sure if this is what you are trying to accomplish but, you could rewrite that function to also work when called from PHP.

    function ids_function ($is_ajax = true) 
    {
        $myArray = array($_REQUEST['id']); 
        if ($is_ajax)
        {
            # NOTE: it die()-s here (after outputting the JSON data)
            wp_send_json( $myArray );
        }
        return $myArray;
    }
    

    Then you can call it from PHP like this:

    $myarray = ids_function (false);
    

    Also consider that PHP and Javascript runs at different times...

    评论

报告相同问题?