AngularJS和PHP的json_encode

时间:2015-09-28 15:33:41

标签: php angularjs

我这里有一个简单的代码,它使用json_encode并在PHP中回显响应。这是我的代码:

app.js

$scope.login = function() {
        var data = {
            username: $scope.login.username,
            password: $scope.login.password
        };

        $http.post('endpoints/login.php', data)
        .success(function(response) {
            if(response.success == "true") {
                alert('nice');
            } else {
                alert('not nice');
            }
        })
        .error(function(response) {
            console.log(response);
        });

    };

的login.php

$data = json_decode(file_get_contents("php://input"));
$stmt = $db->prepare('SELECT * FROM accounts WHERE username=? AND password=?');
$stmt->execute(array($data->username, $data->password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0)
{
    $response = [
        "success" => true
    ];

    echo json_encode($response);
}
else
{
    $response = [
        "success" => false
    ];

    echo json_encode($response);
}

它完美无缺,但这部分不起作用:

if(response.success == "true") {
  alert('nice');
} else {
  alert('not nice');
}

当我添加console.log(response)时,我会Object {success: true} or Object {success: false}

我在这里遗漏了什么吗?谢谢。

1 个答案:

答案 0 :(得分:2)

您需要在if语句中使用布尔值,而不是字符串,因为true != "true"。将您的if语句更改为以下内容:

if(response.success === true) {