AJAX验证数据库内容并将值显示在页面

功能实现:

在jsp页面中填写文本框内容,光标离开文本框,在本页面的相应地方获取数据库中改值所对应的其他数据。

servlet:

request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
// 调用servlet层去数据库查找是否有相同用户名 并返回到页面中的其他记录
String client_id = request.getParameter("client_id");
ClientServices clientServices = new ClientServices();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Client client = clientServices.findClientById(client_id);
if (client != null) {
out.print(URLEncoder.encode(client.getClient_name(), "utf-8"));
} else {
out.print("false");
}
out.flush();
out.close();

jquery:

$(document).ready(function() {
$("#client_id").blur(function() {
$.ajax({
type : 'POST',
url : 'servlet/validServlet?client_id=' + $(this).val(),
data : 'client_id=' + $("#client_id").val(),
success : function(msg) {
if (msg == 'false') {
alert("没有此人");
} else {
//utf-8解码解决中文乱码
$("#clientInfo").html(decodeURI(msg));
$("#clientInfo").attr("value", decodeURI(msg));
}
}
});
});
});

相关推荐