从ajax返回的数据总是在==比较中失败?

时间:2011-08-12 17:05:20

标签: php jquery ajax comparison

此线程出现了一个新问题:jquery form validator never makes ajax call,因为从ajax请求返回的数据是准确的,但在比较时总是失败。这是发出ajax请求的代码:

var pass_form = $('#pass_form');
pass_form.submit( valid_pass_sett );

function valid_pass_sett() {
    //remove old errors - snipped
    pass_old = $('input[name=pass_old]').val();
    pass_new = $('input[name=pass_new]').val();
    pass_confirm_new = $('input[name=pass_confirm_new]').val();

    if (pass_old === "") {
        //display error on form - snipped
        return false;
    } else if (pass_new === "") {
        //display error on form - snipped
        return false;
    } else if (pass_new != pass_confirm_new) {
        //display error on form - snipped
        return false;
    } else if (pass_new.length < 8) {
        //display error on form - snipped
        return false;
    } else {
        $.post("http://www.example.com/ajax/validate.php",{ // async validation
            type: 'valid_old_change_pass', 
            pass_old: pass_old,
            pass_new: pass_new
        }, valid_pass_combo_callback);
        alert('after the ajax call...');
    }
    return false;  // cancel form submission
}

这是请求提交的代码:

$username = $_SESSION['username'];
$pass_old = $_POST['pass_old'];
$pass_new = $_POST['pass_new'];
if (empty($pass_old) || empty($pass_new)) {
    echo "invalid";
} else if (!User::valid_user_pass($username, $pass_old)) {
    echo "invalid_old";
} else if (!Sanitize::is_legal_password($pass_new)) {
    echo "invalid_new";
} else {
    echo "valid";
}

这是处理它的回调函数;回调函数是比较总是失败的函数。

function valid_pass_combo_callback( data ) {

//breakpoint is set here
    if (data == 'valid') {
        //only if the form is valid!
        pass_form[0].unbind('submit').submit();
    }
    else if (data == "invalid_old") {
        //display error on form - snipped
    }
    else if (data == "invalid_new") {
        //display error on form - snipped
    }
    else {
        //it always jumps to here..., even though data *is* the correct value
    }
}

我调试了这段代码,validate.php正在返回"invalid_old"这是正确的(基于我输入的测试数据)。因此,data根据Firebug存储"invalid_old";但是,代码总是跳转到最后一个else语句。为什么比较总是失败?

2 个答案:

答案 0 :(得分:1)

尝试暂时将alert(data.toString());置于支票上方以查看其返回的内容。如果它不是字符串本身,那么它不会返回您期望的数据。

答案 1 :(得分:0)

如评论中所述,添加JQuery的trim函数解决了问题,如图所示:

function valid_pass_combo_callback( data ) {
    trimmed_data = $.trim(data);
    if (trimmed_data == 'valid') {
        //only if the form is valid!
        pass_form[0].unbind('submit').submit();
    }
    else if (trimmed_data == "invalid_old") {
        //display error on form - snipped
    }
    else if (trimmed_data == "invalid_new") {
        //display error on form - snipped
    }
    else {
        //it always jumps to here..., even though data *is* the correct value
    }
}