简体   繁体   中英

javascript: weird behavior of == for strings

This is my code:

    $.ajax({
    type: "POST",
    url: "/myURL",
    success: function(msg){
        alert(msg);
        // aler prints success, but msg != "success" ????
        if (msg == "success") {
           //my code
        } else {
           //other code
        }
     }
});

Something weired happens: the alert dialog prints success, but msg != "success". What am I missing? My php method just returns "success" or "failure" based on some action.

put this before conditionals:

msg= jQuery.trim(msg).toLowerCase();

Assuming by your code you're using JQuery

Try:

if (msg.trim().toLowerCase() == "success")
{...}

You may have to prototype a trim method if it's not supported cross-browser.

Just simply, you can use === for the comparision. May be it useful.

There might be white space around the text.

I can suggest that for a robust way to fix this, return data in a specific format such as JSON .

Add

 dataType:'json'

to your $.ajax configuration, and have the PHP output

header('Content-Type: application/json');
echo json_encode(array('msg'=>'success'));

or 'msg'=>'failure' for the other possibility, of course.

Then in the JS,

success: function(data){
    alert(data.msg);
    if (data.msg == "success") {
       //my code
    } else {
       //other code
    }

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