標籤:javascript ajax
關鍵步驟:
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();}
javascript實現ajax