<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;"><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript"> function load(){ var ajax = getXMLHttp();
ajax.open("POST", "test",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("username=姓名");
}
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> </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>