1.javascript中通过ajax向servlet提交post参数,servlet返回结果
ajax传递中带有参数的如下:
javascript代码如下
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","TEST",true);
//以表单形式提交数据
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=JWY123&&password=123456");
xmlhttp.onreadystatechange = function () {
// 0:请求未初始化(还没有调用 open())。
// 1:请求已经建立,但是还没有发送(还没有调用 send())。
// 2:请求已发送,正在处理中(通常现在可以从响应中获取内容头)。
// 3:请求在处理中;通常响应中已有部分数据可用了,但是服务器还没有完成响应的生成。
// 4:响应已完成;您可以获取并使用服务器的响应了。
//xmlhttp.status==200则交易成功
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerText=xmlhttp.responseText;
}
}
}
</script>
servlet中的doPost代码
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");
PrintWriter write=response.getWriter();
write.println(request.getParameter("name"));
write.println(request.getParameter("password"));
write.flush();
}
}
jsp代码
<body>
<h2>AJAX与servlet通信</h2>
<button type="button" onclick="loadXMLDoc()">测试</button>
<div id="myDiv"></div>
</body>
运行结果
2.ajax使用GET方法获取,
把javascript中ajax的open方法中的POST改为GET如下
xmlhttp.open("GET","TEST",true);
xmlhttp.send();
servlet改为GET方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");
PrintWriter write=response.getWriter();
write.println("这是个GET方法");
write.flush();
}
JSP运行结果