AJAX的POST提交方法,本質(zhì)上來看和GET差不多,有些細小的區(qū)別,POST要提交數(shù)據(jù)時,需要setRequestHeader()方法來提交HTTP頭,然后send()方法中提交數(shù)據(jù)(格式為:"?str=String&str2=String2");str和str2為變量名,String和String2為要發(fā)送的值。
其他與Get差不多。
下面是一個發(fā)送并接收username和passWord的Demon,先創(chuàng)建一個.html文件,名稱隨意,代碼如下:
<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>
接著來創(chuàng)建1.js的Javascript文件,要和.html在同一目錄下,代碼如下:
function fun(){ if(window.xmlHttPRequest){ xmlhttp = new XMLHttpRequest(); }else if(window.ActiveXObject){ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }else{ alert("對象無法被構(gòu)建"); } 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"); //設(shè)置的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 = "耐心等待..."; }}
下面創(chuàng)建一個Servlet注意在web.xml里面的映射名稱要和xmlhttp.open("POST","Servlet1?username="+username+"&password="+password,true);此處的Servlet1一致。
Servlet1,doPost代碼如下:
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()若是成功傳入了數(shù)據(jù)則,在.html也面中顯示輸入的值 } }
截圖如下:
輸入數(shù)據(jù),點擊提交,截圖如下:
新聞熱點
疑難解答