AJAX請求詳解 同步異步 GET和POST
上一篇博文(http://www.cnblogs.com/mengdd/p/4191941.html)介紹了AJAX的概念和基本使用,附有一個小例子,下面基於這個例子做一些探討.
同步和異步
在准備請求的時候,我們給open方法里傳入了幾個參數,其中第三個參數為true時,表示是異步請求:
//1. prepare request xmlHttpRequest.open("GET", "AjaxServlet", true); // XMLHttpRequest.prototype.open = function(method,url,async,user,password) {};
為了模擬服務器的響應,並且不使用緩存內容,我們把服務器代碼改成如下,加了5秒延時:
public class HelloAjaxServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet invoked!"); //mock the processing time of server try { Thread.sleep(5000L); } catch (InterruptedException e) { e.printStackTrace(); } //no cache response.setHeader("pragma","no-cache"); response.setHeader("cache-control","no-cache"); PrintWriter out = response.getWriter(); out.println("Hello World"); out.flush(); } }
下面就可以比較出同步和異步的差別了:
xmlHttpRequest.open()方法,第三個參數設置為async=true時,異步:
點擊按鈕后過了5秒出現Hello World字樣,但是這5秒過程中頁面中的其他地方都是不受影響的,可以操作.
xmlHttpRequest.open()方法,第三個參數設置為async=false時,同步:
同樣是點擊按鈕5秒后出現Hello World字樣,但是這5秒中,按鈕是不可點擊狀態,頁面不可做其他操作.
當使用同步設置時,其實不需要寫回調函數,直接把響應的操作放在后面的語句即可.
注:不推薦使用async=false.
GET和POST
讓我們把原來的程序改得復雜一點,計算兩個輸入框的值.
加入兩個輸入框,然后在發送請求之前獲取它們的值:
<body> <input type="button" value="get content from server" onclick="ajaxSubmit();"><br> <input type="text" value="value1" id="value1Id"> <input type="text" value="value2" id="value2Id"> <div id="div1"></div> </body>
服務器端獲取參數值並返回計算結果:
public class HelloAjaxServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet invoked!"); process(request, response); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doPost invoked!"); process(req, resp); } private void process(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("process invoked!"); String v1 = request.getParameter("v1"); String v2 = request.getParameter("v2"); String result = String.valueOf(Integer.valueOf(v1) + Integer.valueOf(v2)); //mock the processing time of server // try { // Thread.sleep(5000L); // } catch (InterruptedException e) { // e.printStackTrace(); // } //no cache response.setHeader("pragma", "no-cache"); response.setHeader("cache-control", "no-cache"); PrintWriter out = response.getWriter(); out.println("Hello World: " + result); out.flush(); } }
首先用GET方法:
GET方法的參數拼接在url的后面:
xmlHttpRequest.open("GET", "AjaxServlet?v1=" + value1 + "&v2=" + value2, true);//GET xmlHttpRequest.send(null);//GET
POST方法:
xmlHttpRequest.open("POST", "AjaxServlet", true);//POST xmlHttpRequest.send("v1=" + value1 + "&v2=" + value2);//POST requset needs params here, for GET, just leave params empty or set it to null.
注意,使用POST方法提交,在請求發送之前,必須要加上如下一行:
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
完整index.jsp代碼:

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Hello Ajax</title> <script type="text/javascript"> var xmlHttpRequest; function ajaxSubmit() { if (window.XMLHttpRequest) {//in JavaScript, if it exists(not null and undifine), it is true. // code for IE7+, Firefox, Chrome, Opera, Safari xmlHttpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } else { //very rare browsers, can be ignored. } //also, we can handle IE5,6 first using: /* if (window.ActiveXObject) { //code for IE6, IE5 } else { //code for others } */ //send request if (null != xmlHttpRequest) { //get parameters from DOM var value1 = document.getElementById("value1Id").value; var value2 = document.getElementById("value2Id").value; //1. prepare request // xmlHttpRequest.open("GET", "AjaxServlet?v1=" + value1 + "&v2=" + value2, true);//GET xmlHttpRequest.open("POST", "AjaxServlet", true);//POST // XMLHttpRequest.prototype.open = function(method,url,async,user,password) {}; //2. set callback function to handle events xmlHttpRequest.onreadystatechange = ajaxCallback; //3. do sending request action // xmlHttpRequest.send(null);//GET //POST xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttpRequest.send("v1=" + value1 + "&v2=" + value2);//POST requset needs params here, for GET, just leave params empty or set it to null. } } function ajaxCallback() { //alert("test");//this alert will show several times when click the button. if (4 == xmlHttpRequest.readyState && 200 == xmlHttpRequest.status) { var responseText = xmlHttpRequest.responseText; document.getElementById("div1").innerHTML = responseText; } } </script> </head> <body> <input type="button" value="get content from server" onclick="ajaxSubmit();"><br> <input type="text" value="" id="value1Id"> <input type="text" value="" id="value2Id"> <div id="div1"></div> </body> </html>
參考資料:
聖思園張龍老師JavaWeb視頻教程64 POST與GET方式提交Ajax請求的區別,深度解讀HTTP協議.