我们可以在Java中创建一个AJAX示例,用于检查数据库中是否存在给定的电子邮件ID。
需要按照以下步骤操作:
• 在数据库中创建表
• 加载org.json.jar文件
• 创建输入表单
• 创建服务器端页面以使用名称搜索员工
在此页面中,我们创建了一个表单,该表单用于获取输入以查找电子邮件。当单击检查可用性按钮时,它会告知电子邮件ID是否可用。
文件:index.html
<!DOCTYPE html>
<html>
<head>
<title>Email Finder Example</title>
<script>
var request;
function sendInfo() {
var email = document.vinform.email.value;
var url = "emailfinder.jsp?email=" + email;
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('mylocation').innerHTML = val;
}
}
</script>
</head>
<body>
<marquee>
<h1>AJAX Email Checker Example</h1>
</marquee>
<form name="vinform">
<input type="email" name="email" placeholder="enter email" />
<input type="button" onclick="sendInfo()" value="Check Availability" />
<span id="mylocation"></span>
</form>
</body>
</html>
创建服务器端页面以处理请求
在这个jsp页面中,编写数据库代码来搜索电子邮件。
<%@ page import="java.sql.*" %>
<%
String email=request.getParameter("email");
if(email.contains("@")&&email.contains(".")){
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 user100 where email=?");
ps.setString(1,email);
ResultSet rs=ps.executeQuery();
if(rs.next()){
out.print("Unavailable! <img src='unchecked.gif'/>");
}else{
out.print("Available! <img src='checked.gif'/>");
}
}catch(Exception e){
out.print(e);
}
}else{
out.print("Invalid email!");
}
%>