如何在输入姓名时查重
利用ajax获得从前端传过来的数据,通过Servlet进行查重
js代码
$(document).ready(function(){
// 在这里写你的代码...
//alert("d4 jquery");
$("#uname").blur( function() {
// 这里可以写些验证代码
$.getJSON("CKServlet", { uname: this.value }, function(json){
console.log(json);
console.log(json.result);
var rs = json.result+" ";
if(rs=='false'){
$("#unamep").hide();
}else{
$("#unamep").show();
$("#uname").focus();
}
});
});
});
Servlet
TService hs=new TService();
String hid=request.getParameter("uname");
System.out.println(hid);
boolean rs=hs.findByName(hid);
System.out.println(rs);
Map rsmap = new HashMap();
rsmap.put("result", rs);
String rs1=JSONObject.toJSONString(rsmap);
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.getWriter().append(rs1);
}
方法
public boolean findByName(String productName){
boolean flag=true;
try {
conn=jdbc.getConnection();
String sql="select * from user where name=?";
PreparedStatement st=conn.prepareStatement(sql);
st.setString(1, productName);
ResultSet rs=st.executeQuery();
while(rs.next()){
User product=new User();
product.setName(rs.getString("name"));
flag=false;
}
rs.close();
st.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
html
<!DOCTYPE html>
<html>
<body>
<div class="container">
<h2>堆叠表单</h2>
<form>
<div class="form-group">
<label for="email">邮箱:</label>
<input type="email" class="form-control" id="email" placeholder="邮箱">
</div>
<div class="form-group">
<label for="email">姓名:</label>
<input type="text" class="form-control" id="uname" name="uname" placeholder="姓名">
<p style="color:red;display:none" id="unamep" >姓名不能重复</p>
</div>
<div class="form-group">
<label >地址:</label>
<input type="text" class="form-control" id="address" placeholder="地址">
<p style="color:red;display:none" id="addressp" >地址长度不能超过50个字</p>
</div>
<div class="form-group">
<label >班级:</label>
<select class="form-control" id="cname">
<option value = "10">java10班</option>
<option value = "11">java11班</option>
<option value = "12">java12班</option>
</select>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password">
</div>
</div>
<div class="form-group">
<label for="pwd">再次输入密码:</label>
<input type="password" class="form-control" id="pwd2" placeholder="Enter password">
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox"> Remember me
</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>