Json回归原点

时间:2017-10-05 15:37:59

标签: php json ajax

美好的一天,我有以下登录页面。我从我的视图页面使用ajax访问。我尝试在ajax上显示时返回的数据问题我在控制台上收到错误。

  

login.js:35未捕获TypeError:无法读取属性“成功”   未定义       at Object.success(login.js:35)       at i(jquery-2.2.0.min.js:2)       at Object.fireWith [as resolveWith](jquery-2.2.0.min.js:2)       在z(jquery-2.2.0.min.js:4)       在XMLHttpRequest。 (jquery的-2.2.0.min.js:4)

<?php
ob_start();

function __autoload($classname)
{

    require_once("../../database/$classname.php");
}


class userlogin extends database
{

    private $errors = array();
    private $message = array();
    private $redirect = array();
    private $data = array();
    private $username;
    private $password;

    function login()
    {

        if (empty($_POST['username']) || empty($_POST['password'])) {

            $this->message['error'] = "Please enter username and password";
        } else {

            $this->username = $_POST['username'];
            $this->password = $_POST['password'];


            try {
                $this->stmt = $this->dbh->prepare("SELECT adminID,adminEmail,adminPassword,admintype FROM admin where adminEmail = ? ");

                $this->stmt->execute(array(
                    $this->username
                ));

                $this->results = $this->stmt->fetchall();

                if (count($this->results) > 0) {
                    foreach ($this->results as $key => $row) {
                        if (password_verify($this->password, $row['adminPassword'])) {
                            $_SESSION['user']  = $row['adminID'];
                            $_SESSION['email'] = $this->username;
                            $_SESSION['usertype'] = $row['admintype'];

                            switch ($row['admintype']) {
                                case 's':
                                    $this->redirect['redirect'] = "seo/index.php?route=home";
                                    break;
                                case 'a':
                                    $this->redirect['redirect'] = "admin/index.php?route=home";
                                    break;
                            }

                            $this->message['success'] = "ok";

                        } else {

                            $this->message['error'] = "Username and password does not match";
                        }

                    }

                } else {

                    $this->message['error'] = "Username does not exist";
                }

            }
            catch (PDOException $pdo) {

                $this->error = $pdo->getMessage();

                error_log($this->error);
            }

            $this->data['message']  = $this->message;
            $this->data['redirects'] = $this->redirect;

            ob_end_clean();

            echo json_encode($this->data);

        }  

    }


}

if ($_SERVER['REQUEST_METHOD'] == "POST") {

    $login = new userlogin();
    $login->login();
}
?>

和我的js

function proccessLogin(){

        var username = $('input[type="email"][name="email"]').val();
        var password = $('input[type="password"][name="upass"]').val();
        $.ajax({

            type : "POST",
            data : {username:username,password:password},
            url  : "controller/login.php",
            beforeSend : function(){
            $('button').html('Checking...');

            },
            success : function(data){
                console.log(data);

                 if(data.message.success == "ok"){
                    $('#results').removeClass('error');
                    $('#results').addClass('success');
                    $('#results').html('login Success, loading user data..');
                    $('button').html('Loading Profile.. i class="fa fa-spinner fa-pulse fa-1x fa-fw"></i>');
                        var redirectUrl = JSON.stringify(data.redirects);
                        redirectUrl = redirectUrl.replace(/[{"":}]/g, '');
                        var url = redirectUrl.replace('redirect','');
                        setTimeout(' window.location.href = "'+ url + '"; ', 6000);
                }else{

                    $('button').html("Sign in");
                    $('#results').removeClass('success');
                    $('#results').addClass('error');
                    $('#results').html(data.message.error);
                }
            },
            error : function(xhr){

                console.log('Error : ' + xhr);
            }
        });
    return false;   
    }

控制台日志结果:

{"message":{"success":"ok"},"redirects":{"redirect":"seo\/index.php?route=home"}}

我希望能够显示来自json数组的消息,如果成功,我将显示客户消息,否则显示来自响应的内容。问题是属性未定义。

第35行:

if(data.message.success == "ok"){

1 个答案:

答案 0 :(得分:2)

我认为响应数据是String,您需要调用

$.parseJSON(data);

然后才能访问消息然后成功

=============

如果你想使用 dataType:“json”,你需要使用PHP的header()函数将你的JSON作为JSON发送:

/* Send as JSON */
header("Content-Type: application/json", true);

/* Return JSON */
echo json_encode($json);

/* Stop Execution */
exit;