Cookie已添加但未在ajax中显示结果

时间:2017-04-27 04:55:26

标签: php ajax wordpress function

在wordpress中,我正在进行ajax调用

if(!function_exists('re_add_compare')){ 
#compare toggling
function re_add_compare(){
    $post_ids_arr = array();    

    $out = '';
    $compareid = (int)$_POST['compareID'];

            if(array_filter($post_in_cat)){
                $page_id = (int)$multicat[2];
                #existing posts
                $post_ids = isset($_COOKIE['re_compare_'. $page_id]) ? $_COOKIE['re_compare_'. $page_id]: '';

                $dat = '';

                        $arr = explode(",",$post_ids);



                                    $dat = $post_ids.','.$compareid;

                                setcookie('re_compare_'. $page_id, $dat , 3 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);

                }
                #html output
                $out = re_compare_item_in_panel($compareid);
                $count = count($post_ids_arr);
                //$comparing_string = implode(',', $post_ids_arr);
                $comparing_string = $_COOKIE['re_compare_'. $page_id];
            }
        }

    } 

    #generate the response
    $response = json_encode( array( 'content' => $out, 'comparing' => $comparing_string, 'count' => $count, 'pageid' => $page_id ) );

    #response output
    header( "Content-Type: application/json" );
    echo $response;
    exit;
}
}
    add_action('wp_ajax_re_add_compare', 're_add_compare');
    add_action('wp_ajax_nopriv_re_add_compare', 're_add_compare');
jquery

$(document).on('click', '.wpsm-button-new-compare', function(e){

    var thistoggle = $(this);
    var panel = $('#re-compare-bar');       
    var compareID = thistoggle.data('addcompare-id');

    var alltoggles = $('.addcompare-id-' + compareID); 
    alltoggles.addClass('loading');
    if(thistoggle.hasClass('not-incompare')){       
        $.post(translation.ajax_url,{
            action: 're_add_compare',
            compareID: compareID,
            perform: 'add'
        }, function(response){   

            alert('dsf '+response.comparing);

        }); 

    });

问题在于,当第一次运行jquery时,response.comparing为空,第二次显示第一个元素,第三次显示第三个元素。但是cookie有正确的元素,比如第一次运行有1个元素,2个运行有2个元素。

如果我刷新页面,则显示正确的元素数量。

我想在运行ajax之后添加相同的元素应该显示

0 个答案:

没有答案