我试图创建一个登录类,但我的ajax json解析是';没有得到正确的答复


Im trying to create a login class but my ajax json parsing isn't getting a correct response

我试图使用ajax提交表单并返回Business或Admin类型,但我得到了:

JSON.parse:数据意外结束

result=JSON.parse(r);

<input type="text" id="signinemail" placeholder="Email" name="signinemail">
<input type="password" id="signinpassword" placeholder="Password"
name="signinpassword">
<script>
  $(function() { 
    $("#signinsubmit").click(function() {
      var username = $("#signinemail").val();
      $.post("signin.php",
      {
        signinusername: username, signinpassword: $("#signinpassword").val() 
      }     )
       .done( function(r)
      {
        result= JSON.parse(r);  
      if(result["user_type"]=="Business") 
      {
          window.location="profile.php";
      }
      else if(result["user_type"]=="Admin") 
      {
          window.location="requestpage.php";
      }
      });
      });
      });
</script>

这是尝试登录的类。它首先将帖子交给身份验证函数,然后将连接结果返回给对其进行编码的登录函数

<?php
/**
* Logs the User into Website
*/
class Login
{
    private $connection;
    private $result_array = array();
    private $user_type;
    private $id;
    public $username;
    private $password;
    public $loggedIn;
    function __construct()
    {
        $this->username = $_POST['signinemail'];
        $this->password = $_POST['signinpassword'];
        $this->connection = new mysqli('WolfeboroC.db.10688096.hostedresource.com', 'WolfeboroC', 'Brewster#1', 'WolfeboroC');
        $this->authenticate();
        $this->logIn($this->authenticate);
    }
    private function authenticate()
    {
        $query = "SELECT recid, Admin FROM users 
                  WHERE User = '".$this->$username."' 
                  AND password='".$this->$password."' 
                  AND (verified='y' OR admin = 'y') 
                  LIMIT 1";
        $stmt = mysqli_master_query($this->connection, $query);
        $this->result_array = mysqli_fetch_array($stmt);
        return !empty($this->result_array);
    }

private function logIn()
{
    if($result_array->num_rows > 0) 
    {
        if($result_array['Admin']=='y') 
        {
            $this->user_type = "Admin";
            $this->admin($this->result_array);
            $this->loggedIn = true;
        }
        else 
        {
            $this->user_type = "Business";
            $this->business($this->result_array);
            $this->loggedIn = true;
        }
        echo json_encode($this->user_type['user_type']);
    }
}
}
?>

echo json_encode($this->user_type['user_type']);不正确。你的user_type不是一个数组,所以不要试图这样访问它。您可以执行echo$this->user_type并将结果用作javascript中的字符串,或者将值放入数组中,然后json_encode如下:

echo json_encode(array('user_type' => $this->user_type));

尝试使用获取json响应as,

result.user_type

而不是

result["user_type"] 

在login()函数中:json synatrx应该是

echo json_encode(array('user_type' => $this->user_type));

而不是

 echo json_encode($this->user_type['user_type']);