使用ajax登录

时间:2016-09-29 08:42:13

标签: php html ajax

提前感谢..这是我的第一个问题.. 我正在研究php登录脚本,我的脚本几乎准备就绪,这里是一个代码

HTML表格

<input type="text" id="username" />
<input type="password" id="password" />
</input type='submit' id="submit"/>
<div id='result'></div>

<script>
$('#submit').click(function() {
    $.ajax({                    
      url: 'login.php',     
      type: 'post',
      data: { username: $('#username').val(),  password: $('#password').val() }, 
      dataType: 'json',                   
      success: function(data)         
      {
      } 
    }); 
});
</script>

的login.php

if (isset($_POST['username']) && isset($_POST['password'])) {
    $user = mysql_real_escape_string($_GET['username']);
    $pass = mysql_real_escape_string($_GET['Password']);
    $sql = mysql_query("SELECT * FROM users WHERE username='$user' AND password='$pass' LIMIT 1");
    $userCount = mysql_num_rows($sql);
    if ($userCount ==1) 
    {
        echo "login success!";
    }
    else
    {
        echo "Wrong detail!";
    }
}

我想要的是以我的html格式显示login.php结果..我的html格式为div

<div id='result'></div>

有人可以帮帮我..再次感谢所有

更新

我尝试了这个,但它无法正常工作

 success: function(data)         
  {
    $('#result').html(data);
  } 

2 个答案:

答案 0 :(得分:1)

你需要在你的ajax成功函数中添加一行代码。希望它对你有所帮助。

<script>
 $('#submit').click(function() {
$.ajax({                    
  url: 'login.php',     
  type: 'post',
  data: { username: $('#username').val(),  password: $('#password').val() }, 
  dataType: 'json',                   
  success: function(data)         
  {
    $('#result').html(data);
  } 
}); });
</script>

答案 1 :(得分:0)

 success: function(data)         
 {
   // you can do whatever you want to do here..e.g.
   if(data=="login success!"){ ///
    //redirect to home page  
   } 
   else alert("Invalid credentials");
 }