如何在php echo中从表单调用javascript函数?

如何在php echo中从表单调用javascript函数?,javascript,php,html,session,Javascript,Php,Html,Session,下面的代码所做的是确保不允许用户提交评论,除非他使用$\u SESSION['login\u user']超变量登录。但这给了我一个错误。我认为问题是因为我在onsumbit=“return(checkUser())”中调用了一个javascript函数。那里有点不对劲,但我不知道为什么 我有以下代码: <script type="text/javascript"> // notice the quotes around the ?php tag fun

下面的代码所做的是确保不允许用户提交评论,除非他使用$\u SESSION['login\u user']超变量登录。但这给了我一个错误。我认为问题是因为我在onsumbit=“return(checkUser())”中调用了一个javascript函数。那里有点不对劲,但我不知道为什么

我有以下代码:

<script type="text/javascript">  
      // notice the quotes around the ?php tag 
      function checkUser() {     
          <?php
          if(isset($_SESSION['login_user'])){
            $isExist = true;

        }
        ?>
        else{
            $isExist= false;
            alert( "Please register first!" );

        }
      var htmlString="<?php echo $isExist; ?>";
      return isExist;
      }
    </script>

...
...

<?php
echo "<form method='POST' onsubmit="return(checkUser());" action='".setComments($connection, $res['post_id'])."'>
    //echo "<form method='POST' action='".setComments($connection, $res['post_id'])."'>
    <input type='hidden' name='uid' value='".$_SESSION['login_user']."'>
    <input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
    <textarea name='message'> </textarea><br>
    <button type='submit' name='commentSubmit'>Comment</button>
     </form>";
    getComments($connection, $res['post_id']);

?>

....

//注意?php标记周围的引号
函数checkUser(){
否则{
$isExist=false;
警告(“请先注册!”);
}
var htmlString=“”;
返回是存在的;
}
...
...

除了@RonaldT所说的,您还需要了解PHP代码在发送到浏览器之前是在服务器上执行的。因此,在Javascript函数中检查
$\u SESSION['login\u user']
有点愚蠢,因为在用户刷新页面之前,它始终是相同的(只有这样PHP才会重新检查值)

因此,您的功能可以简化如下:

<script type="text/javascript">
    // on page load, define a global variable using PHP
    var isLoggedIn = <?php echo isset($_SESSION['login_user']) ? "true" : "false"; ?>;

    function checkUser() {
        // check that global variable every time checkUser() is called in Javascript
        if (!isLoggedIn) {
            alert( "Please register first!" );
        }

        return isLoggedIn;
    }
</script>

不管OBIVOU的语法是否错误:不要这样做。。我所要做的就是打开控制台任意write
函数checkUser(){return true}
来发送我想要的任何注释。在服务器上验证并提供输出,如果没有访问权限,则不首先提供字段。可能重复的
onsubmit=“return(checkUser());”
必须是
onsubmit=“return(checkUser());”可能重复的@RonaldT不起作用我想像stackoverflow一样做同样的事情。当您未登录时,在stackoverflow中,它仍然显示“发布您的答案”。但当你点击它时,它会强迫你注册。
<?php
if (!isset($_SESSION['login_user'])) {
    echo "Please register to add a comment";
} else {
    echo "<form [...everything else...] /form>";
}

getComments($connection, $res['post_id']);
?>