简体   繁体   中英

Comparing strings, returned from php, in jQuery doesn't work

I am returning a string form php and compare it with another string in jQuery. I am 100% certain that the strings do match (well, at least are of the same value...), but still my if-clause thinks otherwise.

This is the part of my php-script that sets the returning value:

if (!$result){
        echo "false";
        exit();
    }

This is my jQuery that performs the matching:

$.post("registeraccount.php",$(this).serialize(),function(msg){
        //alert the response from the server
        alert(msg + " = " + (msg == "false"));
        if(msg == "false"){
            $("#adminarea").html("Error");

        }else{
            $("#adminarea").html("Success");
        }

   });

No matter that the strings are equal or not equal, it's always "Success" that is printed on the web page.

In the alert I get the following result "false = false". Hence, (msg == "false") is false.

How come the strings are not true when they are equal and how do I fix it?

I suppose that the reason is that msg , your server output, is never exactly "false", due to some line endings that are added or similar things in you PHP script (you could check if msg has the length you expect to verify this hypothesis). In this case, you could try using this:

 if (msg.match(/false/)) {

which does a somewhat less strict comparison if you want, ensuring that the output contains the string "false" (at any position). If it works, I suggest that you use instead this comparison:

 if (msg.match(/^false$/)) {

which guarantees that false be a whole line of your text.

You have to use === to compare for equality in JavaScript.

If you have time have a look at Crockford video series on javascript. It covers this and a lot of other javascript topics.

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