[英]Comparing two identical strings in JQuery returns false
I discovered an interesting problem with an echoed value from an AJAX request of JQuery, which I don't have an answere for: 我发现了一个有趣的问题,该问题与JQuery的AJAX请求中的回显值有关,但我没有以下答案:
My data == "LOCKED"
never returns true (line 13)! 我的
data == "LOCKED"
从不返回true(第13行)!
JQuery -> AJAX call on button-click: jQuery- > AJAX调用,单击按钮:
$.ajax({
url: "ajax/login_ajax_call.php",
method: "POST",
data: { user: usr, password: pwd }
}).done(function(data){
if(data == true || data == "true"){ // -> this works with data beeing true (bool) or "true" (string)
$("#form_submit").submit();
}
else{
console.log(jQuery.type(data)); // -> (string)
console.log(data); // -> "LOCKED"
console.log(jQuery.type("LOCKED")); // -> (string)
if(data == "LOCKED"){ // also tried "===" but it never returns true
[...]
}
else{
[...]
}
}
});
});
PHP (1) -> gets a value returned by a Class(PHP(2)): PHP (1)->获取由Class(PHP(2))返回的值:
include_once("../Classes/Login_check.php");
$lih = new Login_check();
$result = $lih -> check($_POST["user"], $_POST["password"]);
var_dump($result); // -> string(6) "LOCKED"
echo $result;
PHP (2, "Login_check.php"): PHP (2,“ Login_check.php”):
[...]
// also tried:
// $test = "LOCKED";
// var_dump($test); // -> string(6) "LOCKED"
// return $test;
return "LOCKED";
[...]
Tell me if you need further informations! 告诉我您是否需要更多信息! I hope anyone know what causes this problem!
希望任何人都知道导致此问题的原因!
Must be because of some white-spaces or new lines, it is always better to trim the data
. 必须是由于某些空白或换行,最好修剪
data
。 Try this: 尝试这个:
if (data.trim() == "LOCKED") {
You can also use: 您还可以使用:
if ($.trim(data) == "LOCKED") { // using jQuery.
You can try JSON.parse
. 您可以尝试
JSON.parse
。 If value looks like "LOCKED"
on console, it means its like ""LOCKED""
. 如果控制台上的值看起来像
"LOCKED"
,则意味着它的值类似于""LOCKED""
。
As commented, you are getting "\\r\\nLOCKED"
as stringified value, so you can use a regex to replace it. 如前所述,您将获得
"\\r\\nLOCKED"
作为字符串化值,因此可以使用正则表达式替换它。 Following is the updated code. 以下是更新的代码。
Reference - How to remove all line breaks from a string? 参考-如何从字符串中删除所有换行符?
var a = "LOCKED"; var strA = "\\r\\nLOCKED"; var regex = /\\r?\\n|\\r/g; var cleanStr = strA.replace(regex,''); console.log(a); console.log(strA); console.log(strA == a); console.log(cleanStr == a);
Probably due to whitepace somewhere, such as a space before an opening php tag etc. 可能是由于某处的空白,例如php标签前的空格等。
Far better to use a structured data format like json, and return a boolean propery to avoid these issues: 最好使用json之类的结构化数据格式,并返回一个布尔属性以避免这些问题:
$result = $lih -> check($_POST["user"], $_POST["password"]);
$locked = ($result == 'LOCKED');
header('Content-Type: application/json');
echo json_encode(['locked'=>$locked]);
Javascript: Javascript:
if(data.locked){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.