AJAX提交方法(POST)Demon

王朝学院·作者佚名  2016-05-27  
宽屏版  字体: 小 | 中 | 大 | 超大  

Ajax提交方法(POST)DemonAJAX的POST提交方法,本质上来看和GET差不多,有些细小的区别,POST要提交数据时,需要setRequestHeader()方法来提交HTTP头,然后send()方法中提交数据(格式为:"?str=String&str2=String2");str和str2为变量名,String和String2为要发送的值。

其他与Get差不多。

下面是一个发送并接收username和passWord的Demon,先创建一个.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>

接着来创建1.js的Javascript文件,要和.html在同一目录下,代码如下:

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一致。

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()若是成功传入了数据则,在.html也面中显示输入的值 } }

截图如下:

输入数据,点击提交,截图如下:

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有