AJAX成功和失败报告

时间:2016-11-18 20:59:53

标签: javascript ajax

试图弄清楚如何仅在失败时在此弹出窗口内报告。目前这有效,但它提醒成功和失败:

<script>
function Unlock() {
    var pin=prompt("You must enter pin to unlock");
    $.ajax(
    {
        url: 'pin.php',
        type: 'POST',
        dataType: 'text',
        data: {data : pin},
        success: function(response)
        {
            alert(response);
            console.log(response);
        }
    });
}
</script>

我尝试了以下方法,但到目前为止没有运气:

<script>
function Unlock() {
    var pin=prompt("You must enter pin to unlock");
    $.ajax(
    {
        url: 'pin.php',
        type: 'POST',
        dataType: 'text',
        data: {data : pin},
        success: function(response)
        {
            console.log(response);
        },
        error: function(response)
        {
            alert(response);
            console.log(response);
        }
    });
}
</script>

任何帮助将不胜感激。谢谢!

*编辑*

以下是完整代码:

<?php
    $static_password = "1234";
    if(isset($_POST['data'])){
        $submit_password = $_POST['data'];
        if($submit_password == $static_password){
            die("UNLOCK THE RECORD");
        }
        else{
            die("SORRY WRONG PIN");
        }
    }
?>
<html>
<head>
    <script src="js/jquery-3.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<h2>Simple AJAX PHP Example</h2>
<a href="javascript:Unlock();">UNLOCK</a>
<p>Pin is "1234"</p>
<script>
function Unlock() {
    var pin=prompt("You must enter pin to unlock");
    $.ajax(
    {
        url: 'pin.php',
        type: 'POST',
        dataType: 'text',
        data: {data : pin},
        success: function(response)
        {
            alert(response);
            console.log(response);
        }
    });
}
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:4)

对于要执行的错误回调,服务器必须以状态404,500(内部错误)等进行响应。当您编写die('blah');服务器响应状态为200时,以及它已消失的消息。 就AJAX和PHP而言,这是一个成功的请求

您必须检查回复

if($submit_password == $static_password){
    die("UNLOCK THE RECORD");
}

然后:

success: function(response)
    {
       if (response == 'UNLOCK THE RECORD') { /* success */ }
       else { /* failure, do what you will */ }
    }