加载org.json.jar文件
创建输入页面以接收任何文本或数字
创建服务器端页面以处理请求
table1.html
<html>
<head>
<script>
var request;
function sendInfo()
{
var v=document.vinform.t1.value;
var url="index.jsp?val="+v;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try{
request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();
}catch(e){alert("Unable to connect to server");}
}
function getInfo(){
if(request.readyState==4){
var val=request.responseText;
document.getElementById('amit').innerHTML=val;
}
}
</script>
</head>
<body>
<marquee><h1>This is an example of ajax</h1></marquee>
<form name="vinform">
Enter id:<input type="text" name="t1" onkeyup="sendInfo()">
</form>
<span id="amit"> </span>
</body>
</html>
index.jsp
<%@ page import="java.sql.*"%>
<%
String s=request.getParameter("val");
if(s==null || s.trim().equals("")){
out.print("Please enter id");
}else{
int id=Integer.parseInt(s);
out.print(id);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mdb","root","root");
PreparedStatement ps=con.prepareStatement("select * from emp where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
out.print(rs.getInt(1)+" "+rs.getString(2));
}
con.close();
}catch(Exception e){e.printStackTrace();}
}
%>