在jQuery aJax中将整个页面作为响应

时间:2017-09-22 17:55:36

标签: javascript php jquery ajax

我已经尝试将String作为错误消息进行回应,但是我仍然将整个页面扭曲为Jquery Ajax中的响应,但是在正确输入时我被重定向到右页。

PHP

if($_GET['action']=="login"){
if (isset($_POST)) {
    $username = mysqli_real_escape_string($link, $_POST['username']);
    $password = md5($salt.mysqli_real_escape_string($link, $_POST['password']));
    try{
        validateLoginInputs();
         loginUser($username, $password);
          echo "1";
    } catch(Exception $e){
        echo $e->getMessage();     //I think something is wrong with this line
    }
}

功能 - loginUser

    function loginUser($username,$password){
global $link;
    $query =  "SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password' LIMIT 1";
        $result = mysqli_query($link, $query); 
        $row = mysqli_fetch_assoc($result);
        $_SESSION['id'] = $row['id'];
        $_SESSION['username'] = $row['username'];
    if(!$row){
        throw new Exception("Username or Password didn't match");
        }   
}

的jQuery

 else if ($("#loginorsignup").val()==="1") {
  $.ajax({
   url: "action.php?action=login",
   type: "POST",
   data: "username="+$("#username").val()+"&password="+$("#password").val(),
   success: function(response){
     if(response!=1){
      console.log(response);    // getting html of index.php When username or password is incorrect
      $("#userWarnings").html(response).show();  
    }else if(response==1){
      console.log(response);
      window.location.assign("home.php");
    }
       }
     });
}

用于显示错误的容器

 <div class="modal-body">
         <div class="alert alert-warning" role="alert" id="userWarnings">
         </div>

1 个答案:

答案 0 :(得分:0)

我建议更改此功能

function loginUser($username,$password){
    global $link;
    $query =  "SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password' LIMIT 1";
    $result = mysqli_query($link, $query); 
    $row = mysqli_fetch_assoc($result);
    if($row){
       $_SESSION['id'] = $row['id'];
       $_SESSION['username'] = $row['username'];
       return true;
    }
    return false;
}

现在,如果此函数返回true,则表示用户存在。然后

if($_GET['action']=="login"){
if (isset($_POST)) {
    $username = mysqli_real_escape_string($link, $_POST['username']);
    $password = md5($salt.mysqli_real_escape_string($link, $_POST['password']));
    try{
        validateLoginInputs();
        echo loginUser($username, $password) ? '1' : 'Username or Password didn\'t match';

    } catch(Exception $e){
        echo $e->getMessage();
    }
}

您不必在前端(JQuery)代码中进行任何更改。

希望这会对你有所帮助。