Ajax url:参数和检查成功

时间:2015-02-03 09:23:37

标签: javascript php ajax

我不太确定这是如何工作的,但我的成功(数据)价值来自哪里? 我必须在url中返回一个值:php / login.php?

 $.ajax({     
  url: 'php/login.php',    //must i return a value in login.php?                    
  data: {username:username,password:password},
  type: "POST",    
  dataType: 'json',                  
  success: function(data)          
  {
     if(data == true){
        console.log("sdfsdfs   " + data);
        login.submit();
    }
     else{
        console.log("NO DATA PRESENT");
     }       
  } 
     //else do an alert("please lgo in again");    
 });  

在php / login.php中我查询数据库以查看这样的用户是否存在以及密码是否匹配

我的login.php的一部分

 <?php
 echo $username = $_POST['username']; //not echo-ing
 echo $password = $_POST['password'];  
 if ($_POST['login']) //check if the submit button is pressed
 {
   $remember = $_POST['remember'];  
   if ($username&&$password) //check if the field username and password have values
   {
     $dbhost = 'localhost';
     $dbuser = 'root';
     $dbpass = '';

     $connect=mysqli_connect($dbhost,$dbuser,$dbpass) or die("Unable to Connect");  
    mysqli_select_db($connect,"clients") or die("Could not open the db");
    $sql = "SELECT * FROM clients.users WHERE username='$username'";
    $login = mysqli_query($connect, $sql);
    if (mysqli_num_rows($login))
    {
        while ($row = mysqli_fetch_assoc($login)) 
        {
            $db_password = $row['password']; 
            if ($password==$db_password)
            {   
                $loginok = TRUE;
                echo json_encode( true );
            } else {
              echo json_encode( false );
              echo "Please re-enter username and password, they did not match";            
              header("Location: ../login.php");
            }      
   ?>

1 个答案:

答案 0 :(得分:0)

如果要使用ajax返回某些数据,则需要在脚本中回显将由ajax调用的数据。如果请求成功,它会将您在脚本中回显的所有内容返回到您在success function中指定的参数。

success: function(data)          
  {
     // code...
  }

所以“数据”将包含您脚本的结果,然后您可以随心所欲。

修改

好吧,我会像这样解决它

 $db_password = $row['password']; 

        if ($password==$db_password)
        {   
            echo json_encode(array("status" => "ok", "message" => "Login successful!"));
        } else {
          echo json_encode(array("status" => "error", "message" => "Please re-enter username and password, they did not match!"));         
          //header("Location: ../login.php"); you don't need this
        }

你不能回复json,然后是一些文字。你可以,但根本不推荐。