简体   繁体   中英

JavaScript/PHP string equality

I'm running an Ajax call which has a success function which takes in a variable returned from the PHP page like so.

Ajax:

$.ajax ({
    type: "POST",
    url: "loginrequest.php",
      data: 'username=' + username + '&password=' +pass,
    success: function(html){
        console.log(html); // Returns login
        console.log(typeof html); // Returns string
        console.log(html === "login"); // Returns false

        if(html === 'login'){
            window.location.href = 'index.php';
        }
        else if(html === 'false'){
            alert("login failed");
        }
    }
});

PHP:

if($count == 1){
    $_SESSION['user'] = $myusername;
    $return = "login";
    echo json_encode($return);
}
else {
    $return = "false";
    echo json_encode($return);
}

As you can see, I'm trying to implement a simple login page and then redirect the user or display an alert depending on the outcome of the number of rows returned from my database query.

What I don't understand is this:

console.log(html); // Returns "login"
console.log(typeof html); // Returns string
console.log(html === "login"); // Returns false

I tried echo-ing without json_encode() and it still would give me the same results. I was using == , but then I read that it's safer to use === , so I switched to that, but it still won't return true.

You're sending JSON, which means that you're sending the literal bytes:

"login"
"false"

Note the quotes in there. Your JavaScript code either needs to decode the JSON, or compare the raw JSON itself:

 result = JSON.parse(html)
 if (result == "login")

or

 if (html == '"login"')   // Note the quotes

A simple console.log(html) would have shown you what you're dealing with.

If you are using json_encode on the PHP side then you should use:

jQuery.parseJSON on the JavaScript side -

html = jQuery.parseJSON(html);

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