我正在运行一个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。
要解决眼前的问题,请尝试'的console.log(html.trim()=== “登录”);'。 'trim()'在处理纯文本时删除可以附加到响应中的额外空白。作为一种改进,返回JSON来完全避免这个问题。 –
'json_encode'在字符串中加上''',所以你实际上用引号括起来''login''看一看:[https://eval.in/600312](https://eval.in/600312 ) – FirstOne
生成的'json'的快速'var_dump'会很容易地显示出问题;) – FirstOne