我有一个PHP函数,该函数以字符串形式返回true或false(这有效)。如果查看我的JS文件,我会在警报框中显示XMLHttprequest的responseText(这也可以工作)。但是,一旦我尝试将responsestring与另一个字符串进行比较,结果总是错误的。
我已经搜索了stackoverflow,但是没有找到答案。我还尝试了str.equals(“”),以及用php返回布尔值,但似乎没有任何效果。
Javascript:
xhttp.onload = function(){
alert(xhttp.responseText); //Here comes "true" or "false" just like I want it
if(xhttp.responseText == "true"){ //This always gives me "ERROR and then the responseText (which is true or false)
alert("TRUE");
}else if(xhttp.responseText == "false"){
alert("FALSE");
}else{
alert("ERROR" + xhttp.responseText);
}
};
PHP:
if(count($echo)==3){
if($tag==$echo[2]){
echo "true";
break;
}else if($i == (count($fahrten)-1)){
echo "false";
}
}
预期结果:警报为“ TRUE”或“ FALSE” 实际结果:提示“错误”,后跟responseText
我希望你们中的一些人能帮助我,但问题不是太愚蠢,我对学习仍然不屑一顾。
答案 0 :(得分:3)
在进行比较之前尝试修剪responseText
:
xhttp.onload = function(){
var responseText = xhttp.responseText.trim();
alert(responseText); //Here comes "true" or "false" just like I want it
if(responseText == "true"){ //This always gives me "ERROR and then the responseText (which is true or false)
alert("TRUE");
}else if(responseText == "false"){
alert("FALSE");
}else{
alert("ERROR" + responseText );
}
};
答案 1 :(得分:0)
您的xhttp.responseText ==“ true”比较将始终返回false。相反,我将尝试简化您的条件:
xhttp.onload = function(){
alert(xhttp.responseText);
if (xhttp.responseText) {
// true case
alert("TRUE");
}
else {
// false case
alert("ERROR" + xhttp.responseText);
}
};