如何比较我的AJAX响应?

时间:2018-03-15 16:13:32

标签: php ajax

我有一个HTML页面,您可以在其中输入密码以重定向到名为" Files.php"的实习页面。如果输入的密码错误,我会在表单中提供反馈,如果正确,我想重定向到实习页面。

我的HTML看起来像这样:

<form name="download" id="download">
                        <label for="password">Passwort</label><br>
                        <div id="wrongpassword"></div>
                        <input type="password" id="password" name="password" required> <br>
                        <input type="submit" id="submit" value="Download">
</form>

我的AJAX请求是这样的:

$(document).ready(function () {

        var request;

        $("#download").submit(function(event){


            event.preventDefault();

            var $form = $(this);

            var $inputs = $form.find("input, select, button, textarea");

            var serializedData = $form.serialize();

            $inputs.prop("disabled", true);

            request= $.ajax({
                url: "download.php",
                type: "post",
                data: serializedData
            });


    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        if(response=="Success"){
            window.location.replace("Files.php");
        }else{
            $("#wrongpassword").html(response);
        } });});

我的PHP就像这样:

<?php


session_start();
$db = new PDO('mysql:host=localhost;dbname=nachhilfe', 'root', 'secret');



/*if(!$db)
{
exit("Verbindungsfehler: ".mysqli_connect_error());
}
else{
    echo "Success!";
}*/

$pw = ($_POST['password']);

$statement = $db->prepare("SELECT passwort FROM downloads WHERE id= :id");
$result = $statement->execute(array(':id' => 4));
$stored = $statement->fetch();

if(password_verify($pw, $stored['passwort'])){
    $_SESSION['verified'] = true;
    echo "Success";
}
else{
    echo "Wrong password";
}?>

到目前为止,一切正常,除了响应比较if(response=="Success"),它总是假的。

我如何比较我的AJAX响应还是有更好的方法来实现重定向?

1 个答案:

答案 0 :(得分:0)

根据评论,我可能会尝试使用json字符串:

$("#download").submit(function(event){
    event.preventDefault();
    var $form = $(this);
    var $inputs = $form.find("input, select, button, textarea");
    var serializedData = $form.serialize();
    $inputs.prop("disabled", true);
    $.ajax({
        url: "download.php",
        type: "post",
        data: serializedData,
        dataType: 'json',
        success: function(response) {
            if(response.success === true){
                window.location.replace("Files.php");
            }
            else {
                $("#wrongpassword").html(response.msg);
            }
        }
    });
});

然后在php:

<?php
session_start();
$db        = new PDO('mysql:host=localhost;dbname=nachhilfe', 'root', 'secret');
$pw        = $_POST['password'];
$statement = $db->prepare("SELECT passwort FROM downloads WHERE id= :id");
$result    = $statement->execute(array(':id' => 4));
$stored    = $statement->fetch();

if(password_verify($pw, $stored['passwort'])){
    $_SESSION['verified'] = true;
}
# Create a response array
# Note, I am using new syntax for array, you can use array('success'=>false,'msg'=>'Bad Password') if using an unsupported version
$response = (!empty($_SESSION['verified']))? ['success'=>true,'msg'=>'Success'] : ['success'=>false,'msg'=>'Bad Password'];
# Send back the json string to ajax
# Die so you don't get any empty space afterwards by accident
die(json_encode($response));

同样在文档的最后,如果它以php结尾,则不必使用?>关闭。如果脚本会破坏html内容,您只需要关闭它,例如:

?> <div>Stuff</div>

以下是对此的好处的解释:PHP end tag "?>"

修改

由于您在评论{"success":true,"msg":"Success"}行时可以获得dataType: 'json',请尝试使用此版本的ajax:

    $.ajax({
        url: "download.php",
        type: "post",
        data: serializedData,
        success: function(response) {
            // Parse here
            var json = JSON.parse(response);
            // You should get an object now
            alert(json.msg);
            // Now you should be able get the boolean here
            if(json.success === true){
                // Try redirecting this way here
                window.location = "Files.php";
            }
            else {
                $("#wrongpassword").html(json.msg);
            }
        },
        error: function(response) {
            alert(response);
        }
    });