简体   繁体   English

jQuery:如果语句不起作用

[英]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". 基本上,如果变量“ ret”返回一个值,并且如果该值是“ fail”,则应发布Alert:“ Trigger 2”。 However, the problem is the IF statement. 但是,问题是IF语句。 It triggers the Alert:"Trigger 1" and when the conditional statement comes up, it skips it. 它触发警报:“ Trigger 1”,并在条件语句出现时跳过它。

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. 如果响应实际上是fail则问题很可能是响应周围有一些空格,导致if语句的计算结果为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. 如果代码实际上正在运行,则您应该能够使用Chrome或Firefox开发者工具从“发布网址”查看响应标头。 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. 那应该给您实际的响应,并帮助您调试答案,我想它只会返回接近您所拥有的东西,而并不完全是您所拥有的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM