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条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大