普通网友 2014-04-25 18:34
浏览 47

JQuery中的字符串比较

I have this registration form

    <form method="post" action="Register">
        <input type="text" name="name" placeholder="Name"/><br>
        <input type="email" name="email" placeholder="Email" id="email"/><br>
        <span id="taken">This email is already taken!</span>
        <input type="password" name="password" placeholder="Password" />  <br>
        <input type="submit" value="Sumbit" id="button"/>
    </form>

And this JS code is supposed to check whether the email exists in the database or not by calling a servlet using AJAX when focus leaves the email textarea.

$(document).ready(function(){

var field = $("#email");

        $(field).focusout(function(){
              var email = $(field).val();

                $.get("Verify",{"email":email},function(data){
                 alert(data);
                    if(data=="true")
                        $("#taken").css("display","block");

                    if(data=="false")
                        $("#taken").css("display","none");


                });
         }); });

The servlet is returning the correct result (the code works until alert(data)) which is a String that's either "true" or "false", I checked that it's a String by alerting "typeof data". What I want is to display the span $("#taken") if the AJAX response (data) was equal to "true" and hide it otherwise. My problem is that the comparison is not working! I've tried using "===" instead of "==" and I have also tried converting data to boolean by using

var existed = Boolean(data);

to use to use "if(existed)" and "if(!existed)" instead of comparing strings

Nothing worked! I know the answer must be silly but I have truly spent the last two hours looking into it and nothing I have tried worked out. Please help.

  • 写回答

1条回答 默认 最新

  • weixin_33725515 2014-04-25 18:41
    关注

    Use $.getJSON instead of $.get And then change your code to

     if(data)
           $("#taken").css("display","block");
     } else {
           $("#taken").css("display","none");
     }
    

    You also better add Content-type: application/json; charset=utf-8 header to the response from the server

    The reason it doesn't work for you is that data is boolean and when comparing it against a string, the string is also converted to boolean, and both"true" and "false" are converted to TRUE as they are non empty strings

    === won't work as well becausedata and the strings differ in type so the comparison is always falsy

    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能