通过 JS 和 ajax 验证用户登录


Validate user login through JS and ajax

我不确定如何去做,但想通过以下方式验证用户登录:

<form onsubmit="return validateLogIn()" > and
<script>       
function validateLogIn()
{
  $.ajax({                                      
  url: 'login.php',    //checking the login in                     
  data: "",                      
  dataType: 'json',                  
  success: function(data)          
  {
       continue to crud.html
  } 
  else do an alert("please lgo in again");
 }); 
}
</script>

我会有类似上面的东西吗?

您可以使用

此代码

<script>       
function validateLogIn()
{
  var username  = $("#IdOfYourUserFiled").val();
  var password  = $("#IdOfYourPasswordFiled").val();
  $.ajax({                                      
  url: 'login.php',    //checking the login in                     
  data: {username:username,password:password}, //You have to pass user inputs to next page to validate in DB            
  type: "POST",     //Method by which data being transmitted
  dataType: 'json',                  
  success: function(data)          
  {
       continue to crud.html
  } 
  else do an alert("please lgo in again");
 }); 
}
</script>

登录时.php访问用户名和密码的值

$_POST['username'] and $_POST['password']

并编写查询。

我个人在发送数据之前使用beforeSend()进行验证。

$.ajax({
    url:'login.php',
    data:{username:user,password:pass},
    dataType:'json',
    beforeSend:function(xhr){
        if(user.length<7||pass.length<7){
            xhr.abort();//stop process.
            //validation failed etc
        }
     },
     success:function(result){
     }
 });

尝试下面的编码,

function validateLogIn()
{
  username=$("#name").val();
  password=$("#word").val();
  $.ajax({                                      
  url: 'login.php',    //checking the login in                     
  data: "name="+username+"&pwd="+password,                     
  dataType: 'json',                  
  success: function(data)          
  {
       if(data === 0){
            alert("Username or Password is incorrect");
        } else if (data == 1){
            window.open('index.php', '_self');  
        }
  } 
 }); 
}