1、获取XMLHttpRequest对象 自定义my.js
function getXhr() {
//获取AJAX核心对象的封装
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function $(id){
return document.getElementById(id);
}
2、jsp页面
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<!-- 导入脚本 -->
<script type="text/javascript" src="js/my.js"></script>
<script type="text/javascript">
//js代码
function clickMe() {
//调用脚本里的方法
alert(getXhr());
}
//AJAX get请求的实现
function sendGet() {
//获取文本框用户输入的信息
var val = $("getname").value;
//发送数据给后台jsp/servlet
//获取ajax核心对象
var xhr = getXhr();
//建立连接发送给后台Servlet
xhr.open("get", "${pageContext.request.contextPath}/getServlet?username=" + val);
//建立回调函数接收数据
xhr.onreadystatechange=function() {
//4表示请求发送完成,响应就绪
if (xhr.readyState==4 && xhr.status==200){
//document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
$("myDiv").innerHTML = xhr.responseText;
}
}
//发送get请求
xhr.send(null);
}
//AJAX post请求的实现
function sendPost() {
//获取文本框用户输入的信息
var val = $("postname").value;
//发送数据给后台jsp/servlet
//获取ajax核心对象
var xhr = getXhr();
//建立连接发送给后台Servlet
xhr.open("post", "${pageContext.request.contextPath}/getServlet");
//建立回调函数接收数据
xhr.onreadystatechange=function() {
//4表示请求发送完成,响应就绪
if (xhr.readyState==4 && xhr.status==200){
//document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
$("myDiv").innerHTML = xhr.responseText;
}
}
//发送post请求
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("username=" + val);
}
</script>
</head>
<body>
<input type="button" value="点击我获取AJAX对象" onclick="clickMe();">
<hr>
<input type="text" name="name" id="getname">
<input type="button" value="点击发送GET请求" onclick="sendGet();">
<hr>
<input type="text" name="name" id="postname">
<input type="button" value="点击发送POST请求" onclick="sendPost();">
<hr>
<div id="myDiv">
<!-- 显示后台发送来的数据 -->
</div>
</body>
3、接收请求 GetServlet.java
public class GetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String name = request.getParameter("username");
System.out.println("收到客户端name=" + name);
// 响应
response.setCharacterEncoding("utf-8");
response.getWriter().write("<font color='red'>您输入的内容为: " + name + "</font>");
}
}
乱码问题可以参考我之前的博客