Javascript Logic Fail?
I'm really confused on this one. I'm trying to do a simple ajax request, and I have php executing 'echo "true";' if the ajax request is successful, or return a string containing the error if it isn't. I'm using this exact technique elsewhere in the code and it compares as expected (msg != "true") { //do something }. The first function I'll post below works with that method, the second doesn't (also I am checking with Firebug the response is "true", and I've done console.log(typeof msg) to verify it is of type string).
This works as expected (the php echoes "true", and it executes show_step2()):
function step2_register() {
var values = $('.signup .txt').serialize();
$.ajax({
type: "POST",
url: base_url+"login/create_account",
data: values,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup .error_container #error1").html(msg).css("visibility", "visible");
}
else {
show_step2();
}
},
error: function(error) {
alert(error);
}
});
}
This doesn't work (the php echoes "true", but the js always executes the slideDown() part of the code):
function register() {
var data = $("#login_form .input").serialize();
$.ajax({
type: "POST",
url: base_url+"login/register",
data: data,
success: function(msg) {
if (msg != "true") {
$("#login_form.signup #error2").html(msg).slideDown();
}
else {
show_success();
}
},
error: function(error) {
alert(error);
}
开发者_运维问答 });
}
What's going on here?
Your php is likely outputting something else invisible like a newline character after the word "true". Either make sure you call die();
or exit();
right after outputting "true", (and doing everything else you need), or make sure there are no line breaks in your PHP editor before the <?php
and after the ?>
.
You can also check that the string begins with "true" instead of equals "true" by trying something like msg.substring(0,4) == "true"
精彩评论