关键步骤:
1 创建xmlHttpRequest对象;
2 添加回调函数;
3 创建链接;
4 设置请求头信息;
5 发送数据;
var xmlHttpRequest; function chaj(){ if(f1.name.value==null||f1.name.value==""){ alert("不能为空 "); return false; } if(window.XmlHttpRequest){ xmlHttpRequest=new XmlHttpRequest(); }else{ xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttpRequest.onreadystatechange=callBack; var url="My"; xmlHttpRequest.open("post",url,true); xmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttpRequest.send("name="+f1.name.value+"&timeStamp="+(new Date()).getTime()); } function callBack(){ if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){ var result=xmlHttpRequest.responseText; result=result.replace(/(^\s*)|(\s*$)/g, ""); alert(result); //alert(result); } }
注意:xmlHttpServlet为全局变量,在发送数据前不要忘记设置requestHeadder信息。
服务器端:
通过PrintWriter回传信息;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String name1=request.getParameter("name"); String timeStamp1=request.getParameter("timeStamp"); System.out.println(name1+timeStamp1); PrintWriter out=response.getWriter(); out.print("成功"); out.flush(); out.close(); }
时间: 2024-10-14 16:41:54