AJAX的POST提交方法,本質上來看和GET差很少,有些細小的區別,POST要提交數據時,須要setRequestHeader()方法來提交HTTP頭,而後send()方法中提交數據(格式爲:"?str=String&str2=String2");str和str2爲變量名,String和String2爲要發送的值。javascript
其餘與Get差很少。html
下面是一個發送並接收username和password的Demon,先建立一個.html文件,名稱隨意,代碼以下:java
<body> <script type="text/javascript" src="1.js"></script> 用戶名稱:<input type="text" id="username" /><br /> 用戶密碼:<input type="password" id="password" /><br /> <input type="button" onclick="fun();" value="提交"> <br/> <p id="txt"></p> </body>
接着來建立1.js的Javascript文件,要和.html在同一目錄下,代碼以下:web
function fun(){ if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else if(window.ActiveXObject){ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }else{ alert("對象沒法被構建"); } username = document.getElementById("username").value; password = document.getElementById("password").value; xmlhttp.onreadystatechange = handchange; xmlhttp.open("POST","Servlet1?username="+username+"&password="+password,true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //設置的HTTP頭 xmlhttp.send("task=task&msg=msg"); //此處只是爲了證實send()的使用方法,無心義 } function handchange(){ if(xmlhttp.readyState == 4){ if(xmlhttp.status == 200){ document.getElementById("txt").innerHTML = xmlhttp.responseText; } }else{ document.getElementById("txt").innerHTML = "耐心等待..."; } }
下面建立一個Servlet注意在web.xml裏面的映射名稱要和xmlhttp.open("POST","Servlet1?username="+username+"&password="+password,true);此處的Servlet1一致。app
Servlet1,doPost代碼以下:url
response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String username = new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8"); String password = new String(request.getParameter("password").getBytes("ISO-8859-1"),"UTF-8"); String task = new String(request.getParameter("task").getBytes("ISO-8859-1"),"UTF-8"); String msg = new String(request.getParameter("msg").getBytes("ISO-8859-1"),"UTF-8"); System.out.println(username+""+password); if(task.equals("task")){ if(msg.equals("msg")){ out.println(username+""+password);//send()如果成功傳入了數據則,在.html也面中顯示輸入的值 } }
截圖以下:spa
輸入數據,點擊提交,截圖以下:code