ajax 异步 通信 小例子 servlet与 jsp异步 post方法

post请求 url后面加参数 接收不到的,必须 放到send("use"=user)形式

还要加上

 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

servlet

 package cn.itcast.controller;

 import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @WebServlet("/servlet/ServletDemo2")
public class ServletDemo2 extends HttpServlet {
private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("ServletDemo2 doPost running");
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+":"+password);
} }

jsp

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AJAX进行post方式的请求测试</title>
</head>
<body>
<input type="button" id="b1" name="b1" value="测试与服务器的通信"/>
<div id="d1"> </div>
<script type="text/javascript"> window.onload=function(){
document.getElementById("b1").onclick = function(){
//获取xmlhttpRequest对象
var xhr = createXmlHttpRequest();
//注册状态变化的回调函数
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
//什么都不做
}
}
}
//初始化xmlhttpRequest对象,即open
xhr.open("POST", "/ajaxday02/servlet/ServletDemo2?time=" + new Date().getTime());
//设置请求消息头,告知服务器,发送的正文数据的类型。
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//发送数据
xhr.send("username=admin&password=123");
}
}
function createXmlHttpRequest(){
var xmlHttp;
try{ //Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
try{ //Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){}
}
}
return xmlHttp;
} </script>
</body>
</html>
上一篇:IntelliJ IDEA 14使用笔记


下一篇:git换行符之autoCRLF配置的意义