用AJAX,php,jQuery

时间:2017-10-15 14:04:16

标签: php jquery ajax

我有一个这样的登录表单: 我有3个文件:index.htmllogin.phpcustom.js

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Login</title>  
  </head>
  <body>    
    <section>
      <div id="message"></div>    
      <form id="loginform" method="POST">
        <p>Username: <input type="text" id="username" name="username" size=25  />
        </p>
        <p>Password: <input type="password" id="password" name="password" size=25 />
        </p>
        <button id="login" type="submit" name="submit">Login</button>
      </form>    
    </section>   
  </body>
</html>

custom.js看起来就是这样:

$('#login').click ( function() {
  $.ajax({
    type: "POST",
    url: 'login.php',
    data: $('#loginform').serialize(),
    dataType: 'json',
    success: function(data) {
      //alert(data.message);
      // print into ( <div id="message"></div>) on file html.               
    },
  });
  return false;
});

login.php看起来就是这样:

$users = array(
  0 => array(
    "username" => "admin",
    "password" => "admin",
  ),
  1 => array(
    "username" => "demo",
    "password" => "demo",
  ),
);

请检查下面的代码:

for ( $i=0; $i< count($users) ; $i++ ){
  if ( isset($_POST['username'])&& isset($_POST['password']) ) {
    // Please check this code
    if ( $_POST['username'] == $users[$i]['username'] && $_POST['password'] == $users[$i]['password'] ) {
      $data = array('result' => 'success','message' => 'Message sent from server');
      echo json_encode($data);
      // Please check this code
    } else {
      // Please check this code
      $data = array('result' => 'fail', 'message' => 'Message not sent from server');
      echo json_encode($data);
    }
  }
}

我想从表单登录中检查用户(数组),如果匹配用户则使用AJAX打印消息。

请帮我查看我的所有代码并修复它。谢谢大家。

3 个答案:

答案 0 :(得分:0)

我不确定我是否理解你,我的意思是i +的部分......但是......你不能像查询表那样:查询roucount其中user = @_post [user] AND password = @_post [传递],那么如果mysqli rowcount == 1登录,否则死+错误?

答案 1 :(得分:0)

问题是什么?

$i=0; $i< count($users) ; $i++ ) 对我来说看起来像个错误。

尝试$ i&lt; = count $ users。

答案 2 :(得分:0)

首先,您的custom.js需要检查结果是否成功。

for ( $i=0; $i< count($users) ; $i++ ){
    if ( isset($_POST['username'])&& isset($_POST['password']) ) {
        if ( $_POST['username'] == $users[$i]['username'] && $_POST['password'] == $users[$i]['password'] ) {
            $data = array('result' => 'success', 'message' => 'Message sent from server');
            echo json_encode($data);
            // Add return to prevent echo multi json result
            return;
        }
    }
}

// Move the fail code outside the loop otherwise will keep echo fail json
$data = array('result' => 'fail', 'message' => 'Message not sent from server');
echo json_encode($data);
return;

第二,你的login.php返回所有json甚至登录成功与否,所以它应该更新为这样

n=11

这只是一个基于代码的简单解决方案,在PHP中存储非加密密码不是最好的解决方案。

完整代码 https://gist.github.com/stanleybz/ad795c599d9db68e0e28bf6d979ae190