javascript實現ajax

來源:互聯網
上載者:User

標籤: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.