javascript
  • php
  • jquery
  • ajax
  • 2016-07-04 72 views 0 likes 
    0

    我正在运行一个AJAX调用,它有一个成功的函数,它接受像这样从php页面返回的变量。Javascript/PHP字符串相等

    AJAX:

    $.ajax ({ 
        type: "POST", 
        url: "loginrequest.php", 
        data: 'username=' + username + '&password=' +pass, 
        success: function(html){ 
         console.log(html); // returns login 
         console.log(typeof html); // returns string 
         console.log(html === "login"); //returns false 
    
         if(html === 'login'){ 
          window.location.href = 'index.php'; 
         } 
         else if(html === 'false'){ 
          alert("login failed"); 
         } 
        } 
    }); 
    

    PHP:

    if($count == 1){ 
        $_SESSION['user'] = $myusername; 
        $return = "login"; 
        echo json_encode($return); 
    } 
    else { 
        $return = "false"; 
        echo json_encode($return); 
    } 
    

    正如你可以看到,我想实现简单的登录页面,然后将用户重定向或显示这取决于成果警报从我的数据库查询返回的行数。

    我不明白这是:

    console.log(html); // returns "login" 
    console.log(typeof html); // returns string 
    console.log(html === "login"); //returns false 
    

    我尝试回声ING没有json_encode(),它仍然会给我同样的结果。我正在使用==,但后来我发现使用===更安全,因此我切换到了该选项,但它仍然不会返回true。

    +2

    要解决眼前的问题,请尝试'的console.log(html.trim()=== “登录”);'。 'trim()'在处理纯文本时删除可以附加到响应中的额外空白。作为一种改进,返回JSON来完全避免这个问题。 –

    +2

    'json_encode'在字符串中加上''',所以你实际上用引号括起来''login''看一看:[https://eval.in/600312](https://eval.in/600312 ) – FirstOne

    +2

    生成的'json'的快速'var_dump'会很容易地显示出问题;) – FirstOne

    回答

    4

    你发送JSON,这意味着你要发送的文字字节:

    "login" 
    "false" 
    

    注意引号在那里。你的JS代码或者需要到JSON解码,或比较原始JSON本身:

    result = JSON.parse(html) 
    if (result == "login") 
    

    if (html == '"login"') // note the quotes 
    

    一个简单的console.log(html)会显示你你处理什么用。

    +4

    从问题来看,op确实运行了'console.log(html); //返回“login”',但它们可能认为这是控制台显示字符串的方式...... xD – FirstOne

    +0

    解码JSON对我有帮助,谢谢 – ybce

    +0

    json是一个字符串,简单明了,就是它的全部要点。转换为一个简单的字符串进行传输。通过http接收的原始json将始终是一个字符串。 –

    1

    如果你是在PHP端USIG json_encode那么你应该对JavaScript端使用

    jQuery.parseJSON

    html = jQuery.parseJSON(html);

    +0

    对我而言,谢谢。 – ybce

    相关问题