dqvs45976 2013-11-26 11:22
浏览 36
已采纳

实现PHP逻辑到jQuery

In a system I have 3 users, Ben, Shane and Payne, the site functions normally for all users and also have same Menu system. However I am tasked to add one Menu item from core and be visible only for Ben.

So, I added Candy in the Menu item as Ben is kid, but now I cannot change the core in PHP saying

if('Ben' === $user->name) {
  // Show the Candy Menu
}

But I want Candy menu to show only for Ben and hide it from others.

How do I do it with jQuery?

I am not looking to mess up the PHP code like:

<?php if('Ben' === $user->name):?>
  <script ></script>
<?php endif; ?>

I want some logic of PHP to be implemented with jQuery, so, I don't mess with PHP code, instead implement the logic in jQuery. Something like:

//I am mixing PHP and jQuery here, I know it doesn't work but this is what I am looking for.
if('user' === 'Ben') {
  $('#CandyMenu').show();
}

How do I do it?

  • 写回答

2条回答 默认 最新

  • douxian1770 2013-11-26 11:29
    关注

    You will have to make some kind of PHP change, otherwise your JS has no way of knowing who the current user is.

    If you just mean you don't want to mix PHP in the middle of your Javascript code, you could have some one-off PHP at the top of the document that sets up any globals:

    <script>
    var myAppGlobals = {};
    
    myAppGlobals.showCandyMenu = <?php echo ($user->name === 'Ben' ? 'true': 'false'); ?>;
    // or
    myAppGlobals.userName = '<?php echo addslashes($user->name); ?>';
    </script>
    

    and then use

    if (myAppGlobals.showCandyMenu)
        $("#CandyMenu").show();
    
    // or
    
    if (myAppGlobals.userName === 'Ben')
        $("#CandyMenu").show();
    

    from your Javascript later on. You're still mixing PHP and JS, but at least you're doing it all up the top instead of mixed in all over the place.

    Of course, bear in mind that any method you use to set the visibility of a menu from the client side is open to abuse – anyone with JS knowledge would be able to delve in and display that menu option. Whether that's a problem or not is up to you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写