2012-02-15 65 views
0

我檢查了返回字符串是「已添加」或「已用」或「假」,但每次都執行document.write(theresult)的最後一條語句。什麼是問題,我期待如果返回字符串是「使用」然後警報「1」。請幫助,非常感謝。Ajax返回字符串在if語句中意外的結果

function add_member() 
    { 
    var xmlhttp; 

    if (window.XMLHttpRequest) 
     {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
     } 
    else 
     {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    xmlhttp.onreadystatechange=function() 
     { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
     // document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
     var theresult = xmlhttp.responseText; 

      if (theresult == "used") { 
      alert("1"); 
      } 

      else if (theresult == "added") { 
      alert("2"); 
      } 

      else if (theresult == "false") { 
      alert("3"); 
      } 

      else 
      { 
      document.write(theresult); 
      } 



     } 
     } 
xmlhttp.open("GET","add.php?addnew=true&email=" + document.memberform.email.value + "&tel=" + document.memberform.tel.value,true); 
xmlhttp.send(); 
} 
+0

在這種情況下添加快速跟蹤線以進行調試總是明智的。在上面的例子中,你可以做的是,在'var theresult = xmlhttp.responseText'行後面,檢查'theresult'包含的內容。你可以使用'alert(「[」+ theresult +「]」)'或'console.log(「[」+ theresult +「]」)''。我添加了這些方括號,因爲它們可以幫助您在出現額外空白導致程序失敗的情況下進行調試。另外,處理非結構化數據很少是一件好事。 – 2012-02-15 05:14:23

回答

0

@JBL即使設置了一個字符串,Ajax響應文本也不是純字符串。你無法比較它。如果你想傳遞一個字符串並進行比較,請在響應頭中進行。