简体   繁体   English

基于PHP会话变量的JavaScript表单验证

[英]Javascript form validation based on PHP session variables

I have a login area of my site, and on login I set a session variable $_SESSION['logged_in'] = true . 我有网站的登录区域,登录后设置了会话变量$_SESSION['logged_in'] = true

Now I also have lots of forms and things where users can input comments. 现在,我还有很多表单和东西,用户可以在其中输入评论。 Obviously in my PHP validation I check the user is logged in simply using the session variable, but I want javascript validation too because I can make the user experience slicker that way. 显然,在我的PHP验证中,我只是简单地使用会话变量来检查用户是否登录,但是我也希望进行JavaScript验证,因为这样可以使用户体验更加流畅。

$("body").on("click", ".submit", function(e){
    e.preventDefault();
    if (user == logged in){
        ...AJAX call to php file....
    }
})

So how do people generally do the bit where I check the user is logged in using javascript? 那么人们通常如何使用javascript检查用户登录的位置? ie if user == logged in if user == logged in

  • You can of course check user permissions by AJAX (with JSON for example), but this will provide some additional latency. 您当然可以通过AJAX(例如,使用JSON)检查用户权限,但这会带来一些额外的延迟。

  • You can just write a value to global JS scope like this: 您可以像这样将值写入全局JS范围:

    if ( userIsLogged() ) { echo "<script>document.mysite.userlogged = true;</script>"; }

    then you can check document.mysite.userlogged variable. 然后您可以检查document.mysite.userlogged变量。

  • You can also set a cookie in PHP, wich can be obtained in JavaScript. 您也可以在PHP中设置cookie,而在JavaScript中则可以获取。 To get cookies properly in JS see that: Javascript getCookie functions 要在JS中正确获取cookie,请参见: Javascript getCookie函数

  • If you don't want to inject JS code, you can set some attribute like: 如果您不想注入JS代码,则可以设置一些属性,例如:

    <div id="comments" data-logged="<?php echo $isLogged; ?>"> ... </div>

    And get it by jQuery: 并通过jQuery获取:

    if ( $("#comments").attr('data-logged') == 1 ) {

  • you can provide logged/notlogged specific functionality for the whole page by generating JS file, like: <script type="text/javascript" src="http://yoursite.com/somefile.php"> and generate it in php dynamically, but be aware of caching ! 您可以通过生成JS文件来为整个页面提供已记录/未记录的特定功能,例如: <script type="text/javascript" src="http://yoursite.com/somefile.php">并在php中动态生成,但是要注意缓存!

Personally i would go to data-XXX attribute if tou want to personalize single block, and global JS variable if you check logged condition many times in JS. 就个人而言,如果您想个性化单个块,则我将转到data-XXX属性,如果您在JS中多次检查记录的条件,则将转到全局JS变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM