jQuery'If'语句字符串比较不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3233422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:04:05  来源:igfitidea点击:

jQuery 'If' statement string comparison not working

jqueryajaxstringcomparisonif-statement

提问by williamg

I'm having a very hard time trying to do something very simple. Here's the code:

我很难尝试做一些非常简单的事情。这是代码:

        if(data == 'success') {

            alert('foo');

        } else {

            alert(data);

        }

I've simplified it, but that's all that's necessary to understand what's going on. the variable 'data' is a result of an AJAX call, if that makes any difference. The problem is that it always goes to the 'else' statement and it alerts 'success', which it shouldn't if it goes to the 'else'. Any idea what's going on here?

我已经简化了它,但这就是了解发生了什么所必需的。变量“数据”是 AJAX 调用的结果,如果这有什么不同的话。问题在于它总是转到“else”语句并警告“成功”,如果它转到“else”则不应该。知道这里发生了什么吗?

EDIT: Here's the full AJAX code in jQuery:

编辑:这是 jQuery 中的完整 AJAX 代码:

$.post("/manage_sites.php", {before:before, edit:after}, function(data){

        if(data == success) {

            alert('blah');

        } else {
            alert(data);
        }
    });

And then in the PHP response:

然后在 PHP 响应中:

...code....
$update = mysql_query("UPDATE users SET feeds = '$afterFeed' WHERE username = '$name'") or     die("Query Failed");

if($update) {

    echo  'success';  //this is the 'string' that is being given to 'data'
}

回答by Nick Craver

You can fix it on the client side using $.trim()like this:

您可以使用以下方法在客户端修复它$.trim()

if($.trim(data) == 'success') {

Or, a better approach would be removing the new-line coming from the server-side, probably an erroneous new-line in your PHP somewhere, check before or after the <? ?>block, this is most often where they crop up.

或者,更好的方法是删除来自服务器端的换行符,可能是 PHP 中某处错误的换行符,在<? ?>块之前或之后检查 ,这通常是它们突然出现的地方。

Or, just exit after outputting your content, like this:

或者,在输出内容后退出,如下所示:

if($update) {
  echo 'success';
  exit();
}

回答by karlw

You can remove the trailing ?> in your file, if it is the last line in the file. I want to response to the comments to the original issue, but i don't see how.

您可以删除文件中的尾随 ?>,如果它是文件中的最后一行。我想回应对原始问题的评论,但我不知道如何回应。

回答by syyu

Client side validation working fine.

客户端验证工作正常。

$.trim() fine.

Thank You Nick. It took me long to understand why its not working ...

谢谢尼克。我花了很长时间才明白为什么它不起作用......