ajax 小例子

function createXMLHttpRequest() {
	if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	}
}

function startRequest(url) {
	createXMLHttpRequest();
	xmlHttp.open("GET", url, true);
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.send();
}

function handleStateChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			document.getElementById("myDiv").innerHTML = xmlHttp.responseText;
			alert(xmlHttp.responseText);
		}
	}
}

function showHint() {
	var f = document.regForm;
	var str = f.txt1.value;
	var xmlhttp;
	if (str.length == 0) {
		document.getElementById("txtHint").innerHTML = "";
		return;
	}
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.open("GET", 'CheckName.jsp?uname='+str, true);
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
		}
	}
	
	xmlhttp.send();
}

 jsp:

<%
response.setHeader("Pragma","No-Cache");
response.setHeader("Cache-Control","No-Cache");
response.setDateHeader("Expires", 0); 
String a[]=new String[30];
a[0]="Anna";
a[1]="Brittany";
a[2]="Cinderella";
a[3]="Diana";
a[4]="Eva";
a[5]="Fiona" ;
a[6]="Gunda";
a[7]="Hege";
a[8]="Inga";
a[9]="Johanna";
a[10]="Kitty";
a[11]="Linda";
a[12]="Nina";
a[13]="Ophelia";
a[14]="Petunia";;
a[15]="Amanda";
a[16]="Raquel";
a[17]="Cindy";
a[18]="Doris";
a[19]="Eve";
a[20]="Evita";
a[21]="Sunniva";
a[22]="Tove";
a[23]="Unni";
a[24]="Violet";
a[25]="Liza";
a[26]="Elizabeth";
a[27]="Ellen";
a[28]="Wenche";
a[29]="Vicky";

String q=request.getParameter("uname").toUpperCase();

String hint="";
if(q.length()>0){
    for(int i=0;i<30;i++){
       if(a[i].toUpperCase().indexOf(q)==0){
           if(hint.length()==0){
               hint=a[i];
           }else{
               hint=hint+ ","+a[i];
           }
       }
    }
}
//PrintWriter aaa = response.getWriter();
if(hint.length()==0){
    out.print("no suggestion");
}
else{
    out.print(hint);
}
%>

 后台:

请在下面的输入框中键入字母(A - Z):


姓氏:

建议:

 

运行效果如下:

 
 

你可能感兴趣的:(ajax 小例子)