Javascript 从xmlhttp.responseText获取布尔值
我有这样的代码来设置变量isItemLocked的值Javascript 从xmlhttp.responseText获取布尔值,javascript,ajax,Javascript,Ajax,我有这样的代码来设置变量isItemLocked的值 function authorItem(itemNumber){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }else{ xmlhttp=new ActiveXObject("Micros
function authorItem(itemNumber){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
url ="Some URL";
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var isItemLocked = xmlhttp.responseText;
if(isItemLocked){
alert('Item has been Closed.Click OK to go to Search Page');
window.location = "SOME OTHER URL";
}else{
var url ="SOME OTHE URL 1";
location.href = url;
}
}
}
}
isItemLocked的返回布尔值为true。但每次我都要转到其他URL。有解决方案吗?尝试以下方法:
var isItemLocked = xmlhttp.responseText.toString().toLowerCase() == "true";
responseText
将作为字符串返回,因此您需要检查它是否等于字符串“true”xmlhttp。responseText
不返回布尔值,它返回一个字符串,“false”
为true
执行字符串比较
if (isItemLocked === 'true') {
// Do one thing
} else if (isItemLocked === 'false') {
// Do a different thing
} else {
// You have an unexpected response from the server and should handle the error
}
xmlhttp.responseText
中究竟返回了什么?字符串是否表示true/false
?一个数字?不幸的是,这看起来像W3School的易受种族条件影响的XHR代码。您需要努力消除其中的全局变量。修改了我的代码,如函数authorItem(itemNumber){if(window.XMLHttpRequest){xmlhttp=new-XMLHttpRequest();}else{xmlhttp=new-ActiveXObject(“Microsoft.xmlhttp”);}url=“SOME-url”;xmlhttp.open(“GET”,url,true);xmlhttp.send(null);xmlhttp.onreadystatechange=function(){if(xmlhttp.readyState==4){var-isitemlock=xmlhttp.responseText.toString();if(isitemlock==Y'){alert('项目已关闭。单击“确定”转到搜索页面');window.location=“SOME URL 1”;}else{var-URL=“SOME-OTHER-URL”;location.href=URL;}}}但仍不工作?我是否遗漏了任何内容?数据中可能有空白。