来自PHP脚本的jQuery调用模式

时间:2015-04-06 14:44:47

标签: javascript php jquery modal-dialog

我正在创建一个登录脚本,用于检查表中是否存在用户。

如果用户不存在,我想使用jquery打开一个模态窗口,让用户知道有错误。

 <?php
   include("../include/database.php");
   if(isset($_GET['loginSubmit']))   // form submit button
   {
 // form username and password values
     $username = strip_tags(mysqli_real_escape_string($dbc, trim($_GET['username'])));
     $password = strip_tags(mysqli_real_escape_string($dbc, trim(md5($_GET['password']))));

 // set query
     $select = "SELECT username, fullname, userlevel, `password` FROM users WHERE username = '".$username."'"; 
 // run query
     $query = mysqli_query($dbc, $select);
 // get the results
     $row = mysqli_fetch_array($query);
 // set the results to variables to be used in sessions
     $dbusername = htmlentities(stripslashes($row['username']));    
     $dbfullname = htmlentities(stripslashes($row['fullname']));
     $dbuserlevel = htmlentities(stripslashes($row['userlevel']));
     $dbpassword = htmlentities(stripslashes($row['password']));

 // check if the database password matches the user password
     if($dbpassword == $password)
     {
 // if yes, set the sessions and direct to main page
       $_SESSION['username'] = $username;
       $_SESSION['fullname'] = $dbfullname;
       $_SESSION['userlevel'] = $dbuserlevel;
       header("Location:main.html"); 
     }
     else
     {
 // if no match, this is where I want the javascript to show the modal
       echo ("<script language='javascript'>
              $('#errLoginModal').modal('show');  // this is jquery and I know it's incorrect
              window.location.href='index.php'
              </script>");
     }  
 ?>

我仍在尝试使用JavaScript,jQuery和PHP。随着Stack Overflow,我越来越好了。

我希望PHP脚本在用户名/密码检查失败时使用JavaScript / jQuery触发模态窗口。我甚至不确定这是否是最好的方法。

我知道上面的代码不正确。我的意思是它没有显示一个模态窗口。

另一方面,我可以添加警报,它会像这样触发警报:

 else
 {
   echo ("<script language='javascript'>
          alert(test);
          window.location.href='index.php'
          </script>");
 }

这很有效。我只是希望能够展示模态。

2 个答案:

答案 0 :(得分:2)

您可以尝试包含js文件。

 }else{

   echo `<script src="you_file.js"></script>`
 }

    //you_file.js

(function ($){
    $(document).ready(function() {
        alert(`test`);
        $('#errLoginModal').modal('show');  
        window.location.href='index.php';
    })
})

当然包括之前的jquery

答案 1 :(得分:1)

我假设您正在使用Bootstrap打开模态窗口,因为您使用.modal('show')。确保在HTML <head></head>中包含jquery以及bootstrap js文件。

如果模态窗口位于对$('#errLoginModal').modal('show');的调用之下,则需要使用jQuery .ready事件,该事件将在DOM完全加载后触发docs。< / p>

所以你可能应该这样:

else {
    echo ("<script language='javascript'>
        $( document ).ready(function() {
          $('#errLoginModal').modal('show');
        });
        </script>");
}