简单ajax应用实例:ajax+jsp实现用户名验证(2)
//回调函数
function callback(){
//判断对象的状态是否交互完成
if(xmlhttp.readyState == 4){
//判断http的交互是否成功
if(xmlhttp.status == 200){
//获取服务器端返回的数据(文本)
var resbonseText = xmlhttp.responseText;
//将数据显示在页面上
var divNode = document.getElementById("result");
//设置元素节点中的html内容
divNode.innerHTML = responseText;
}
}
}
后台servlet程序代码:
public class AJAXServer extends HttpServlet{
protected void doPost(httpServletRequest request, HttpServletResbonse resbonse)throws ServletException,IOException{
doGet(request, resbonse);
}
protected void doGet(httpServletRequest request, HttpServletResbonse resbonse)throws ServletException,IOException{
try{
request.setCharacterEncoding("utf-8");
resbonse.setContentType("text/html; charset=utf-8");
PrintWriter out = resbonse.getWriter();
String old = request.getParameter("name");
if(old == null || old.length() == 0){
out.println("用户名不能为空!");
}else{
String name = old;
if(name.equals("zhangsan")){
out.println("用户名[" + name + "]已经存在!");
}else{
out.println("用户名[" + name + "]尚未存在,可以使用!");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}