我需要驗證用戶名,所以當用戶輸入用戶名時,它應該發送到後端以驗證其可用性。我有以下代碼,但有疑問從後端接收可用或不可用的消息。如何異步接收來自後端的消息?
function verifyUsername(value){
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("mymessage").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("get","verifyUsername?username="+value,false);
xmlhttp.send();
}
....
<div id="mymessage"></div>
....
服務器端的僞碼(實際執行:JAVA)
....
if(verify(username))
return "Username is not available";
else
return "username is available";
謝謝,但如何將它關聯到onclick?所以一旦用戶鍵入數據並點擊文本框觸發此功能? – J888
這有幾種方法。你聽一個事件,點擊,keydown等我會更新我的答案,以反映這一點 –