简体   繁体   English

处理ajax响应异常

[英]Handling ajax response exceptions

I am currently handling a form with php and calling it via an ajax request, i want to handle exceptions showing a small div instead of the basic popup so i did multiple if conditions based on the responsetext, however one of the exceptions doesnt get handled This exception is the empty fields exception it always shows the wrong username or pw instead 我目前正在使用php处理表单并通过ajax请求调用它,我想处理显示小div而不是基本弹出窗口的异常,因此我根据响应文本做了多个if条件,但是其中一个异常没有得到处理例外是空字段例外,它总是显示错误的用户名或密码

here is the ajax call 这是ajax电话

function sendLogin(){
    username = $('#loginEmail').val();
    password = $('#loginPassword').val();
    a = $.ajax({
        type: 'post',
        data: 'username='+username+'&password='+password,
        url: '/account/login.php',
        async: false,
    });

    if(a.responseText == "LoggedIn"){
        $("#WrongPW_Error").fadeOut("fast");
        $("#Empty_Error").fadeOut("fast");
        $("#LoggedIn").fadeIn("fast");
        setTimeout(location.reload(),2200);
     }
        else if(a.responseText == "Empty_Fields") {
          //alert(a.responseText);
          $("#WrongPW_Error").fadeOut("fast");
          $("#Empty_Error").fadeIn("fast");
     }
        else if(a.responseText == "Wrong_Credentials") {
          //alert(a.responseText);
          $("#Empty_Error").fadeOut("fast");
          $("#WrongPW_Error").fadeIn("fast");
    }
}

and here is the php file 这是PHP文件

<?php
if(!isset($_POST['username']) || !isset($_POST['password'])){
    echo "Empty_Fields";
    die();
}

$username = $_POST['username'];
$password = $_POST['password'];

$hashed_pass = hash("sha512", $password);
$stmt = $dbh->prepare("SELECT Count(email)as total, username from Users where email = :username and password= :password");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $hashed_pass, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total = $row['total'];
if($total == 1){
    session_start();
    $_SESSION['user'] = $username;
    $_SESSION['user_name'] = $row['username'];
    echo "LoggedIn";
    die();
}
else{
    echo "Wrong_Credentials";
    die();
}
?>

You are not performing the correct check in PHP to see if the POST variables are empty. 您没有在PHP中执行正确的检查以查看POST变量是否为空。

Read: What's the difference between 'isset()' and '!empty()' in PHP? 阅读: PHP中的'isset()'和'!empty()'有什么区别?

isset($_POST['username'])

will return true if the POST parameter exists, even if its content is an empty string. 如果POST参数存在,即使其内容为空字符串也将返回true You need both tests: isset AND empty . 您需要两个测试: issetempty

if(!isset($_POST['username']) || !isset($_POST['password'])){
    echo "Missing_Param";
    die();
}

if(empty($_POST['username']) || empty($_POST['password'])){
    echo "Empty_Fields";
    die();
}

Edit: I did not notice that you're using async: false ; 编辑:我没有注意到您正在使用async: false ; leaving this answer for reference. 留下这个答案供参考。 In general it's a good idea to use non-blocking calls in JS so other UI elements aren't affected. 通常,在JS中使用非阻塞调用是一个好主意,这样其他UI元素就不会受到影响。

$.ajax does not return anything; $.ajax不返回任何内容; it's an asynchronous call that will call a function when it completes. 这是一个异步调用,它将在完成时调用一个函数。 You'll need to do something like this: 您需要执行以下操作:

$.ajax({
  // other arguments here
  success: function(data) {
    // handle success
  },
  error: function() {
    // handle error
  }
});

More examples available here and here . 此处此处提供更多示例。

Instead of calling die() on your PHP code, send an error response. 发送错误响应,而不是在PHP代码上调用die() Call http_response_code(401) (not authorized response). 调用http_response_code(401) (未经授权的响应)。 Second issue is that $.ajax doesn't return a response and async = false has been deprecated and should not be used. 第二个问题是$.ajax不返回响应,并且async = false已被弃用,不应使用。 Instead, define two functions for success and failure and just set those as the success and error parameters of your AJAX request. 相反,为成功和失败定义两个函数,并将它们分别设置为AJAX请求的successerror参数。

    $.ajax({
         type: 'post',
         data: 'username='+username+'&password='+password,
         url: '/account/login.php',
         async: false,
         success: successFunction,
         error: errorFunction
     });

    function successFunction(response){
        $("#WrongPW_Error").fadeOut("fast");
        $("#Empty_Error").fadeOut("fast");
        $("#LoggedIn").fadeIn("fast");
        setTimeout(location.reload(),2200);

    }
    function errorFunction(response){
            $("#WrongPW_Error").fadeOut("fast");
            $("#Empty_Error").fadeIn("fast");
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM