2016-07-20 134 views
0

目标:使按钮“添加到收藏夹”和页面上的选定商品的地图。 我的收藏后存储在JS-cookie的阵列为什么wp_send_json返回null

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

ID中的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); 

} 

在页面选择商品我打电话finction ids_function()和页面返回null的地图。但是在console.log中,我看到了需要数组。如何让它在我的页面? TNX!

+0

你能后产生'null'代码?如'$('。mydiv')。html('response ='+ response);'并输出'response = null'? – gregn3

+0

'<? ids_function(); ?>'这会产生'null'。我需要在php数组中的id。 –

+0

你怎么知道它是空的?你说它通常将内容写入console.log? 该函数'wp_send_json()'也调用'die()',所以它永远不会以PHP返回。 – gregn3

回答

0

不知道这是否是你想要完成的,但是,你可以重写那个函数,当从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; 
} 

然后你就可以像这样从PHP调用它:

$myarray = ids_function (false); 

同时认为,PHP和JavaScript运行在不同的时间...

+0

$ myarray = ids_function(false); print_r($ myarray); //返回Array([0] =>) - 不工作 –

+0

试试这个:'echo'

' . print_r ($_COOKIE, true) . '
';'。看看你的数据是否在那里。也尝试打印$ _REQUEST的内容。看看它是否在那里。如果它在Cookie中,则应在页面加载时由浏览器发送。然后你可以读取ids_function()中的数据。例如'if(!$ is_ajax){/ *从$ _COOKIE或$ _REQUEST * /}读取数据' – gregn3

+1

非常感谢! '$ _COOKIE'就是我需要的! '$ posts = get_posts($ _ COOKIE ['likes']);'工作正常! –