简体   繁体   中英

jquery: if statement does not work

The code below is very simple. Basically, if variable "ret" returns a value and if the value is "fail" it should post Alert:"Trigger 2". However, the problem is the IF statement. It triggers the Alert:"Trigger 1" and when the conditional statement comes up, it skips it.

I'd like to know if I'm doing something wrong. Thank you.

$(function() {
    var body = $(document).find("body");    
    body.on("submit", "#form-user-profile", function (e) {
        var data = $(this).serialize();
        var url  = $(this).attr("action");
        $.post(url, data, function(ret) {
            alert("Trigger 1"); //  Triggers alert
            if (ret == "fail") {
                alert("Trigger 2"); //  does not trigger alert
            }
        });
        return false;
    });
});

If the response actually is fail then most likely the problem is some whitespace surrounding the response, causing the if statement to evaluate to false. This can be solved by trimming the response:

if ($.trim(ret) == "fail") {

If the code is actually running, you should be able to view response headers from the Post URL using Chrome or Firefox dev tools. That should give you what the actual response is and help you debug the answer, I imagine its simply returning something close to what you have, but not exactly what you have.

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