简体   繁体   中英

AngularJS and PHP's json_encode

I have a simple code here that uses json_encode and echo out the response in PHP. Here is my code:

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);
}

It works perfectly but this part doesn't work:

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

When I add console.log(response) I get Object {success: true} or Object {success: false} .

Am I missing something here? Thank you.

You need to use a boolean in your if statement, not a string because true != "true" . Change your if statement to the following:

if(response.success === true) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM