Ajax请求在成功后显示JSON

时间:2016-05-11 13:06:21

标签: php jquery json ajax

我正在尝试通过AJAX进行简单登录,并且除了在成功回调提醒响应后,浏览器显示JSON响应时,它正常工作:

  

{ “状态”: “成功”, “用户名”:1234}

我以前曾多次使用同一段代码而没有任何问题,但我想我错过了为什么会发生这种情况的一些知识?当然有一些修改,但AJAX部分在PHPJquery中都是相同的,我无法弄清楚我做错了什么。

这是Jquery:

$('#btnLogin').on('click', function(){
   login();
});

function login(){
var un = $('#loginUn').val();
var pwd = $('#loginPwd').val();

 $.ajax({
     url: 'index.php?page=login', 
     type: 'POST',
     dataType: 'json',
     data: {'un': un, 'pwd': pwd},
     success: function(data){
            alert("You are logged in as "+data.username);
     },
     error: function (request, error, data) {
        console.log(arguments);
        alert(" Can't do because: " + error+ " DATA: " + data);
    }
 });

}

PHP控制器:

include_once 'models/login.class.php';
$user = new Login( $dbh );


// If the form is submitted
if(isset($_POST['un'])){

    // Check if fields are empty
    $fields = array('un', 'pwd');

    $error = false; //No errors yet

    //Loop trough each field
    foreach($fields AS $fieldname) { 
        if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
        $error = true; //Yup there are errors
        }
    }
    // If there are no errors
    if(!$error) { 
        $un     = $_POST['un'];
        $pwd    = $_POST['pwd'];

        $user->checkUser($un, $pwd );
    }   
}   
$view = include_once"views/login-html.php"; 
return $view;

最后生成响应的模型:

class Login {
private $dbh;

// Connect to database
public function __construct ( $pdo ) {
    $this->dbh = $pdo;
}

public function checkUser ($un, $pwd ){
    $sth = $this->dbh->prepare('SELECT password, username FROM employees WHERE username = ?');

    $sth->execute(array($un));

    //Getting the data from db
    while($r=$sth->fetch()){
            $password   = $r['password'];
            $username   = $r['username'];
    }

    if($un == $username && $pwd == $password){

        $array = array('status' => 'success', 'username' => $username);
        // echo "<script>alert('You are logged in as ".$username."');</script>";
        // echo "<script>window.location.href='index.php';</script>";
        // echo json_encode(array('status' => 'success', 'username' => $username);
        $forEcho = json_encode($array);

        echo $forEcho;          
    }else{
        echo json_encode(array('status' => 'failure'));
    }
    exit;
}// End checkUser function
}// End of class

这是HTML:

<div class="container text-center">
    <div class="col-sm-4 col-sm-offset-4">
        <h1>Login</h1>

         <form role="form" method="post">

            <div class="form-group">
                <div class="row">
                    <h3>Username</h3>
                        <div class="input-group">
                            <div class="input-group-addon">
                                <span class="fa fa-user"></span>
                            </div>
                            <input type="text" name="un" class="form-control" id="loginUn" placeholder="Please type in your username">
                        </div>
                </div>
            </div>

            <div class="form-group">
                <div class="row">
                    <h3 id="lblPassword">Password</h3>
                    <div class="input-group"> 
                        <div class="input-group-addon">
                            <span class="fa fa-key"></span>
                        </div>
                        <input type="password" name="pwd" class="form-control" id="loginPwd" placeholder="Please type in your password">
                    </div>
                </div>
            </div>

            <button id="btnLogin" type="¨button" name="btnLogin" class="btn btn-success">Submit</button>

        </form>
    </div>
</div>

如果有人能告诉我哪里出错了,我真的很感激!一直在寻找一个没有结果的解决方案/解释几个小时。

编辑:添加了HTML。成功回调中的警报工作正常,但是当关闭它时,JSON就是显示在空白屏幕上的所有内容。从来没有发生过这件事。

2 个答案:

答案 0 :(得分:3)

type属性的值无效:

type="¨button"

...因此按钮恢复为默认值并且是提交按钮。

您正在查看正常提交表单的结果,而不是使用Ajax。

作为短期解决方案,请移除¨。从长远来看,您应该采用unobtrusive JavaScript作为最佳做法。

答案 1 :(得分:0)

我打赌btnLogin是一个提交按钮,呵呵..返回false或阻止默认设置阻止表单提交..

$('#btnLogin').on('click', function(e){
    e.preventDefault();
    login();
});