【问题标题】:jQuery ajax pass variable to php session, but php session not store itjQuery ajax 将变量传递给 php 会话,但 php 会话不存储它
【发布时间】:2021-01-07 10:19:14
【问题描述】:

我尝试将类添加到正文中,并将其存储在 php 会话中。 我使用 ajax 来做,但是 php session 不存储它。 变量传递正确。 会话在 php 函数中启动。

(function ($) {
    jQuery(document).on('click', '#wcag-button', function () {
        $('body').attr('id', 'wcag-theme');
        $('#wcag-button').hide();
        $('#wcag-button-off').show();

        var data = {
            'action': 'wcag_contrast_on',
            'bodyClass': 'wcag-theme'
        }
        $.post(Theme_Variables.ajax_url, data, function(response) {
            console.log(response);
        });
    });
})(jQuery);


add_action('wp_ajax_wcag_contrast_on', 'wcag_contrast_on');
add_action('wp_ajax_nopriv_wcag_contrast_on', 'wcag_contrast_on');

    function wcag_contrast_on() {
        session_start();
        $body_class=$_POST['bodyClass'];
        $_SESSION["usertemplate_css"] = $_POST['bodyClass'];
        //echo 'You sent ' . $body_class;
        echo ($_SESSION["usertemplate_css"]);
        $response['message']    = "Successfull Request";
        echo json_encode($response);
        wp_die();
    }

我也尝试在标题中启动会话,但不工作。

【问题讨论】:

    标签: php html ajax wordpress


    【解决方案1】:

    请使用 WordPress Init Hook 尝试以下解决方案

    add_action('init', 'set_session'); 
    function set_session() {
     if(!session_id()){
          session_start();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 2018-05-09
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 2019-01-26
      相关资源
      最近更新 更多