dongliqian6245 2017-04-18 07:15
浏览 26
已采纳

获取在jquery中使用的php函数信息

I'm using a Wordpress plugin to create users for my site and I need to check if a user if logged in and then execute something in a jquery function. The plugin states they have public functions set up for such things. I'm not sure if I have this set up correctly, whether the user is logged in or out it is coming up "loggedout". The public function is in my functions.php file of my theme and is :

function loggedin() {
    $FEUP = new FEUP_User;
    if ($FEUP->Is_Logged_In()) {
        echo "loggedin";
    } else {
        echo "loggedout";
    }
}

my jquery function is :

var user = "<?php loggedin(); ?>";
if(user == "loggedin") {
    console.log("user is logged in");
}else {
    console.log("user is logged out");
}

This is a screenshot from the makers of the plugin as to how to implement the public function to see if the user is logged in:enter image description here

  • 写回答

2条回答 默认 最新

  • dongquanjie9328 2017-04-18 09:38
    关注

    You might consider using wp_localize_script() to ensure that your javascript variable is being output where the jQuery code can see it.

    Here is an example. This would be your php plugin code to enqueue your jQuery file:

    wp_enqueue_script('my-script-handle', plugins_url( '/whatever_location/myscript.js', __FILE__), array('jquery'));
    

    You can then add javascript variables from php using the wp_localize_script() function, which will output your variables inside script tags where your script can use them:

    wp_localize_script('my-script-handle','my_plugin_vars', array('logged_status' => 'some_value'));
    

    All together it could look like this:

    PHP:

    $FEUP = new FEUP_User;
    $logged_status = $FEUP->Is_Logged_In() ? 'loggedin' : 'notloggedin';
    
    wp_enqueue_script('my-script-handle', plugins_url( '/whatever_location/myscript.js', __FILE__), array('jquery'));
    wp_localize_script('my-script-handle','my_plugin_vars', array('logged_status' => $logged_status));
    

    JS:

    if(my_plugin_vars.logged_status == 'loggedin') {
        console.log("user is logged in");
    } else {
        console.log("user is logged out");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部