2010-11-11 94 views
2

我有我這樣的代碼來獲取變量isItemLocked的值。從xmlhttp.responseText獲取一個布爾值

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;  
         } 
       } 
      } 
} 

一個returnning布爾值true爲isItemLocked.But每次我去一些其他的解決方案URL.Any?

+0

在'xmlhttp.responseText'返回什麼_exactly_?是一個字符串說'真/假'?一個號碼? – Oded 2010-11-11 13:06:42

+0

這看起來不幸像W3School的競爭條件容易XHR代碼。你需要努力消除它的全局。 – Quentin 2010-11-11 13:10:14

回答

4

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 
} 
+0

謝謝隊友...真的很愚蠢的錯誤從我身邊 – 2010-11-11 13:13:17

+0

修改我的代碼,如函數authorItem(itemNumber){if(window.XMLHttpRequest){xmlhttp = new XMLHttpRequest(); } else {xmlhttp = new ActiveXObject(「Microsoft.XMLHTTP」); } url =「某些網址」; xmlhttp.open( 「GET」,網址,真實); xmlhttp.send(NULL); xmlhttp.onreadystatechange = function(){if(xmlhttp.readyState == 4){var isItemLocked = xmlhttp.responseText.toString();如果(isItemLocked =='Y'){alert('Item has closed.Click OK to go to Search Page'); window.location =「某些網址1」; }其他{var url =「其他網址」; location.href = url; }}}}但仍然沒有工作?我錯過了什麼? – 2010-11-11 13:46:28

+0

數據中可能存在空白區域。 – Quentin 2010-11-11 23:22:31

1

試試這個:

var isItemLocked = xmlhttp.responseText.toString().toLowerCase() == "true"; 

responseText是回來爲一個字符串,所以你需要檢查它是否等於「true」字符串