1、get方法 //获取AJAX对象
function getAjax(){ var ajax=null; if(window.XMLHttpRequest){ Majax=new XMLHttpRequest(); } else{ Majax=new ActiveXObject("Microsoft.XMLHTTP"); } return Majax; }失去焦点函数
function getUser(){ var username=document.getElementsByName("name")[0].value; /* 获取ajax对象 */ var Majax=getAjax(); Majax.onreadystatechange=function(){ if(Majax.readyState==4&&Majax.status==200){ var txt=Majax.responseText; document.getElementById("respuser").innerHTML=txt+":"+username; } } Majax.open("get", "ajax111.do?name="+username, true); Majax.send(null); //用post mAjax.open("post","ajax1.do",true); mAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //发送 mAjax.send("name="+document.getElementById("name").value); }servlet代码 地址*.do
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String useName=req.getParameter("name"); PrintWriter out=resp.getWriter(); if("ajax".equals(useName)){ out.write("用户名已存在"); }else{ out.write("用户名通过"); } if(req.getRequestURI().contains("index.do")){ req.setAttribute("namesensitive", req.getParameter("name")); req.getRequestDispatcher("sensitive.jsp").forward(req, resp); } }用jQuery
<script type="text/javascript"> $('#name').blur(function(){ var inputName=$('#name').val(); $.ajax({ url:"ajax.dow", type:"post", data:{name:inputName}, dataType:"text", success:function(data){ $('#desc').text(data); }, complete:function(a,b){ alert(a);//Ajax对象 alert(b);//运行环境 }, error:function(a,b,c){ alert(a); alert(b); alert(c);//错误信息 } } ); }) </script>