dongliqian6245 2017-04-18 15: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 17: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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改