在java中使用ajax搜索示例

在此示例中,我们正在创建一个表单,以使用Java中的Ajax按名称搜索员工。在这里,我们编写了两层应用程序代码,以使应用程序易于理解。你可以根据自己的标准编写数据库代码。
在Java中使用AJAX创建搜索示例的步骤你需要执行以下步骤:

  1. 在数据库中创建表
  2. 加载org.json.jar文件
  3. 创建输入表格
  4. 创建服务器端页面以使用名称搜索员工
在数据库中创建表【在java中使用ajax搜索示例】在此示例中,我们使用的是oracle 10g数据库。在这里,我们创建了一个表“ emp911”,其中包含以下数据。
加载org.json.jar文件下载此示例,我们已将org.json.jar文件包含在WEB-INF / lib目录中。
创建输入表格在此页面中,我们创建了一个表单,该表单从用户获取输入以按名称搜索员工。当用户通过键盘按下后释放键时,将调用searchInfo()函数。 Ajax代码写在searchInfo()函数内部。
< !DOCTYPE html> < html> < head> < script> var request=new XMLHttpRequest(); function searchInfo(){ var name=document.vinform.name.value; var url="index.jsp?val="+name; try{ request.onreadystatechange=function(){ if(request.readyState==4){ var val=request.responseText; document.getElementById('mylocation').innerHTML=val; } }//end of function request.open("GET", url, true); request.send(); }catch(e){alert("Unable to connect to server"); } } < /script> < /head> < body> < h1>Search Employee< /h1> < form name="vinform"> < input type="text" name="name" onkeyup="searchInfo()"> < /form>< span id="mylocation">< /span> < /body> < /html>

创建服务器端页面以处理请求在此jsp页面中,我们正在编写数据库代码以搜索以给定名称开头的员工。
< %@ page import="java.sql.*" %> < % String name=request.getParameter("val"); if(name==null||name.trim().equals("")){ out.print("< p>Please enter name!< /p>"); }else{ try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle"); PreparedStatement ps=con.prepareStatement("select * from emp911 where name like '"+name+"%'"); ResultSet rs=ps.executeQuery(); if(!rs.isBeforeFirst()) { out.println("< p>No Record Found!< /p>"); }else{ out.print("< table border='1' cellpadding='2' width='100%'>"); out.print("< tr>< th>Id< /th>< th>Name< /th>< th>Email< /th> < th>Address< /th>< th>City< /th>< th>State< /th>< th>Country< /th>< /tr>"); while(rs.next()){ out.print("< tr>< td>"+rs.getString(1)+"< /td>< td>"+rs.getString(2)+"< /td>< td>"+rs.getString(3)+"< /td> < td>"+rs.getString(4)+"< /td>< td>"+rs.getString(5)+"< /td>< td>"+rs.getString(6)+"< /td> < td>"+rs.getString(7)+"< /td>< /tr>"); } out.print("< /table>"); }//end of else for rs.isBeforeFirst con.close(); }catch(Exception e){out.print(e); } }//end of else %>

输出量请参阅搜索表。
现在输入员工姓名。如果未找到员工姓名,则会显示“未找到记录!”。信息。
现在输入表中存在的员工姓名。现在它将显示以给定名称开头的所有记录。

    推荐阅读