2013-03-23 190 views
1

好的...所以我的代碼非常簡單。唯一的問題是被調用onreadystatechange的函數永遠不會被執行。我放入一個警報來顯示readyState和分別顯示爲1和0的xmlhttp的狀態。我不明白爲什麼國家沒有改變。另外我確實知道一切正常。我在警報框中顯示我從窗體中獲取的用戶名......它正確顯示。請幫我在這裏....我只是不明白這一點...onreadystatechange函數永遠不會被調用

function checkAvailability() { 
    var xmlhttp; 
    if (window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
    } else { 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    if (xmlhttp) { 
     var regform = document.getElementById("regform"); 
     var username = regform.username.value; 
     xmlhttp.open("POST", "http://localhost:8080/UsernameAvailability", true); 
     xmlhttp.onreadystatechange = function() { 
      alert(xyz); 
     } 
     xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
     xmlhttp.send("username=" + username.value); 
    } 
} 
+1

你有意構建你自己的ajax函數庫嗎?如果是這樣,那很酷,但如果您只需要獲得Ajax功能並繼續工作,請查看jquery.com。 – 2013-03-23 14:36:50

回答

3

你需要切換的xmlhttp.onreadystatechangexmlhttp.open調用爲了確保onreadystatechange回調開幕前註冊。

xmlhttp.onreadystatechange = function() { 
    alert(xyz); 
}; 
xmlhttp.open("POST", "http://localhost:8080/UsernameAvailability", true); 
+0

好吧...所以現在我只是分開它,並創建另一個函數被稱爲onreadystatechange和驚喜!警報工作。但我的工作並沒有結束......當readyState == 4和狀態== 200以及這些條件沒有得到滿足時,我需要做一些處理。 readyState和狀態的值只是1和0 ... – rashmi1412 2013-03-23 15:04:00

相關問題