Ajax参数的传递(POST)

<p>采用POST方式发送Ajax请求时,Servlet中不能获取参数的解决方法:需要对XMLHttpRequest设置XMLHttpRequest属性。 <br />页面代码如下:</p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:2a29181d-9b34-44fc-be7f-37a72081d01c" class="class"> <pre style="width: 1022px; height: 358px; overflow: auto" class="brush: jscript; gutter: true; first-line: 1; tab-size: 3; toolbar: true; width: 1022px; height: 358px;">&lt;html&gt; &lt;head&gt; &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt; &lt;script type=&quot;text/javascript&quot;&gt; function load(){ var ajax = getXMLHttp();

ajax.open(&quot;POST&quot;, &quot;test&quot;,true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');//这句很关键,否则服务器检测不到参数  

ajax.onreadystatechange = function(){
	if(ajax.readyState == 4){
		if(ajax.status == 200){
			var ret = ajax.responseText;
			document.getElementById('content').innerHTML=(ret);
		}
	}
}
ajax.send(&quot;username=姓名&quot;);

}

function getXMLHttp(){ var xmlhttp; try{ xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ try{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){ try{ xmlhttp = new XMLHttpRequest(); }catch(e){} } }

return xmlhttp;

} </script> </head> <body> <div id="content"></div> <script type="text/javascript">load();</script> </body> </html></pre>

<!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin. http://dunnhq.com --></div>

<p>&#160;</p>

<p>Servlet代码如下:</p>

<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:c073aefb-e8ce-42f1-b476-a5d21a1e2e5d" class="class"> <pre style="width: 1022px; height: 238px; overflow: auto" class="brush: java; gutter: true; first-line: 1; tab-size: 3; toolbar: true; width: 1022px; height: 238px;">public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); }

@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String usr = req.getParameter("username"); resp.getWriter().write("用户名:"+usr); }

}</pre>

<!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin. http://dunnhq.com --></div>

转载于:https://my.oschina.net/amath0312/blog/130922

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值