如何在HTML中看到使用AJAX的动态JSON响应?

时间:2015-02-26 23:10:47

标签: javascript php jquery html ajax

对于练习我只用一个用户(没有数据库)制作登录表单,现在我遇到了问题,因为我不知道如何通过AJAX从JSON获取错误消息以显示在结果 (我在firebug中看到它们)。我不知道哪里出错了。 这是我的scriptLogin.php代码:

<?php

const USERNAME = 'user1';
const EMAIL = 'me@me.me';
const PASSWORD = 'pass1';


if (!empty($_POST)) {
    $username = null;
    $email = null;
    $password = null;


    if (isset($_POST['contactUser'])) {
        $username = (string)$_POST['contactUser'];
    }

    if (isset($_POST['contactPass'])) {
        $password = (string)$_POST['contactPass'];
    }

    if (isset($_POST['contactEmail'])) {
        $email = (string)$_POST['contactEmail'];
    }

    $errMessage = [];

    if ($username != USERNAME || $email != EMAIL || $password != PASSWORD ) {
        $errMessage['contactInput'] = 'Please enter valid user,mail and pass!';
    }

    if (empty($username)) {
        $errMessage ['contactUser'] = 'Please enter a username!';
    }

    if (empty($email)) {
        $errMessage ['contactEmail'] = 'Please enter your E-Mail!';
    }

    if (empty($password)) {
        $errMessage ['contactPass'] = 'Please enter a password!';
    }



    if (!empty($errMessage)) {
        http_response_code(400);
    } else {
        http_response_code(200);
    }

    header('Content-Type: application/json');

    echo json_encode($errMessage);

    exit();
}?>

这是我的login.html代码

<div id="result"></div>
<form method="post" action="loginScript.php" id="myForm" >
        <input type="text" name="contactUser" id="username" placeholder="Username" />
        <input type="text" name="contactEmail" id="email" placeholder="Email" /> 
        <input type="password" name="contactPass" id="password" placeholder="Password" />        
        <input type="submit" id="btnLogin" value="Login" />
</form>

这是我的AJAX代码

$(document).ready(function() {
        $('#myForm').submit(function(){
            $.ajax({
                type: "POST",
                url: "loginScript.php",
                dataType:'json',
                data: $('#myForm').serialize(),

                success: function (data) {
                    $("#result").html("Success - LogIn !");
                },
                error: function(){
                    $.getJSON("loginScript.php",
                        function(json)
                        {
                            var output = json.contactInput;
                            output += json.contactUser;
                            output += json.contactEmail;
                            output += json.contactPass;

                            $("#result").html(output);
                        }
                    )
                } 
            });
           return false;
        });
    }); 

1 个答案:

答案 0 :(得分:0)

尝试:

$("#result").html(JSON.stringify(output));