我正在尝试比较两个似乎包含相同值但不起作用的字符串。
这是我的代码:
ABC.prototype.is_in_DB = function () {
var ans = "";
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
ans = (xmlhttp.responseText);
}
return ans;
}
xmlhttp.open("POST", "ABC_DB.php", false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("id=" + this.get_id() + "&name=" + this.get_type() + "&description=" + this.get_description() + "&kind=" + this.get_kind());
var check = "true";
console.log("this is ans type " + typeof (ans));
console.log("this is ans length " + ans.length);
console.log("this is ans " + ans);
console.log("this is check type " + typeof (check));
console.log("this is check length " + check.length);
console.log("this is check " + check);
if (ans === check) {
console.log("the if is true ");
return true;
} else {
console.log("the if is false ");
return false;
}
}
PHP文件可以工作,它的结尾看起来像这样(文件中没有更多的echo命令)
if ($row_cnt>0){
echo('true');
} else {
echo('false');
}
当我打印字符串的值时,我收到以下内容
这是 ANS 类型字符串
这是 ANS 长度 5
这是真的
这是检查类型字符串
这是支票长度 4
这是检查真
如果为假
你知道我该如何比较它吗?
尝试使用 ans.trim() 并使用 == 而不是 ===似乎 ans 也可以有一个尾随字符,例如 '
在这里胡乱猜测,但由于"answers"的长度是 5,但值是"true",我敢打赌那里有一个空格。尝试在回声之前添加修剪,看看是否可以修复它。
似乎您的响应文本带有一些空格。
尝试使用:if (ans.trim() == check)
尝试消除ans
和check
不是同一个对象的可能性,使用==
而不是===
感谢大家。我发现对我有用的是添加以下两行
x=(xmlhttp.responseText);
ans=x.replace(/^'s*/,'').replace(/'s*$/,'').toLowerCase();
我面临的问题是由于额外的空格。这条线消除了它们。