在此示例中,我们正在与数据库进行交互。你无需付出任何额外的努力。仅在服务器端页面中写入数据库逻辑。
【带有数据库的ajax示例】在此示例中,我们在index.jsp文件中编写了服务器端代码。
通过jsp用数据库创建ajax示例的步骤你需要执行以下步骤:
- 加载org.json.jar文件
- 创建输入页面以接收任何文本或数字
- 创建服务器端页面以处理请求
创建输入页面以接收任何文本或数字在此页面中,我们创建了一个获取用户输入的表单。当用户按下任意键时,将调用sendInfo()函数。我们已经在此函数内编写了所有ajax代码。
每当就绪状态发生变化时,我们都将调用getInfo()函数。借助innerHTML属性,它会将返回的数据动态写入网页。
<
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>
创建服务器端页面以处理请求在此jsp页面中,我们为给定的ID打印ID和雇员的姓名。
<
%@ 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();
}
}
%>
输出量

文章图片

文章图片