如何处理成功' if - else'在ajax调用和响应中?

时间:2017-05-29 07:07:22

标签: javascript php jquery ajax

我在AJAX中有一个代码,用于检查密码是否存在。如果是,则发送" OK"作为输出"不正确"作为输出。我希望在AJAX调用成功处理程序的响应基于此做任务。怎么办呢?我想如果密码是正确的,删除​​表单元素中的禁用属性,否则我希望我希望该表单元素的属性保持为禁用状态。    像这样的AJAX代码:

$("#currentpassword").keyup(function() {
    var name = $(this).val();

    if (name.length > 5) {
        $("#result").html('checking...');



        $.ajax({

            type: 'POST',
            url: 'checkPassword.php',
            data: $(this).serialize(),
            success: function(data) {
                if (data == "1") {
                    $("#result").html(data);
                    $("#newpassword").removeAttr("disabled");
                    $("#confirmpassword").removeAttr("disabled");

                } else {
                    $("#result").html(data);

                }
            }


        });
        return false;
    } else {
        $("#result").html('');
    }
});

checkpassword php文件如下所示:

 <?php

  include_once 'includes.php';




// Submitted form data 

         $currentpassword=$_POST['currentpassword'];


        $result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$row = mysqli_num_rows($result);

if($row!=1) {
    echo "<span style='color:red;'>Incorrect Password !!!</span>";;

}
else {
    echo "OK";
}

// Output status

 ?>

1 个答案:

答案 0 :(得分:0)

好方法是PHP文件看起来像这样

<?PHP

header('Content-type:application/json;charset=utf-8');

include_once 'includes.php';

$currentpassword=$_POST['currentpassword'];

$result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$count  = mysqli_num_rows($result);

if($count! = 1) {
   header('HTTP/1.1 401 Unauthorized', true, 401);
    echo json_encode('In Correct Password');
} else {
    header('HTTP/1.1 404 Not Found', true, 404);
    echo json_encode('Not Found');
}

你的Jquery将是

$.ajax({

            type: 'POST',
            url: 'checkPassword.php',
            data: $(this).serialize(),
            success: function(data) {
               // Only 200 comes here
            }, error(jqXHR, exception) {
              // All errors except 200 comes here.
            }


        });

希望这有帮助