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开发者_Python百科 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
}
精彩评论