简体   繁体   English

JQuery中的字符串比较需要说明

[英]String Comparison in JQuery Needs Explanation

I'm having a trouble finding out an explanation with my code.. After echoing back a value from php and received by 'response' in jquery, I'm trying to compare a String from the value of response.. 我在查找代码解释时遇到麻烦。.从php回显了一个值并在jquery中通过“ response”接收到之后,我试图从response的值中比较一个String。

Not working: 无法运作:

success:function(response)
            {
                if (response=='added successfully')
                {
                   alert("");
                }
            },

I found a solution over the internet by putting up 'response' inside the $.trim()..And other solution i found out is to put 'exit();' 我在Internet上通过在$ .trim()中放置“响应”找到了一个解决方案。我发现的另一个解决方案是将“ exit();”放入 after the echoing the value in PHP.. 在回显PHP中的值之后。

Working 工作中

success:function(response)
            {
                if ($.trim(response)=='added successfully')
                {
                   alert("");
                }
            },

AND

    if ($resultset)
    {
        echo 'added successfully';
        exit();
    }

Can anyone tell why the first code is not working (hoping for an easy way of explaining it)? 谁能说出为什么第一个代码不起作用(希望以一种简单的方式来解释它)?

when you make ajax call say "echofile.php", in response it will give you empty leading and trailing space. 当您进行ajax调用时,说“ echofile.php”,作为响应,它将给您空的前导和尾随空间。 in jsp it has one page directive to trim the output. jsp它具有一页指令来修剪输出。 <%@ page trimDirectiveWhitespaces="true" %> or you can trim response in your jquery success callback function. <%@ page trimDirectiveWhitespaces="true" %>或您可以在jquery成功回调函数中修剪响应。

To confirm my point you can put alert in your "not working" code. 为了证实我的观点,您可以在“不起作用”代码中添加警告。 It would definitely have a leading or trailing space. 它肯定会有前导或尾随的空间。 so you have to trim it on either on client side or on the server side 所以您必须在客户端或服务器端进行修剪

Most likely you have some spaces after the ?> at the end of the script. 脚本末尾的?>后面很可能有一些空格。 PHP outputs everything outside of <?php ... ?> literally. PHP从字面上输出<?php ... ?>之外的所有内容。 The exit() causes the script to stop immediately, so it never gets to the end with the spaces. exit()导致脚本立即停止,因此它永远不会以空格结束。

Make sure that <?php is the very first line of the script. 确保<?php是脚本的第一行。 And you don't need ?> at the end of the script at all. 而且您根本不需要在脚本末尾使用?> If you don't need to go back into literal HTML mode, just end the script in PHP execution mode. 如果不需要返回原义的HTML模式,只需在PHP执行模式下结束脚本即可。

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

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