今天用了纯js代码写ajax和后台交互,写好了最开始没得问题,但是前端接收后台数据的时候遇到问题了。一直获取不到值,原来是我理解错了,获取后台的相关操作必须写到那个状态变化监听器里面。也就是需要写到onreadystatechange里面。最开始我一直以为获取后台的操作应该在发送请求(send)之后。弄了很久,最后还是一同学帮我看到了错误。
前台代码为:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>
<title>ajax学习</title>
<script>
window.οnlοad=function(){
document.getElementById("btn1").οnclick=function(){
//发出已补请求
//1/得到xhr对象
var xhr=getXHR();
//2.注册状态变化监听器
xhr.onreadystatechange=function(){
if(xhr.readyState==4)
{
if(xhr.status==200)
{
alert("服务器响应了");
document.getElementById("mytext").innerHTML=xhr.responseText;
}
}
}
//3.建立与服务器的连接
xhr.open("GET","AjaxServlet"+"?time="+new Date().getTime());
//4.向服务器发出请求
xhr.send();
}
}
</script>
</head>
<body>
<button id="btn1">点我呀</button>
<div id="mytext"></div>
</body>
</html>
后台servlet代码为:
package com.levi.servletajax;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AjaxServlet
*/
public class AjaxServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AjaxServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
System.out.println("ajax后台交互成功");
PrintWriter write=response.getWriter();
write.println("我是输出的文字<br>");
write.println("姓名:花2不谢<br/>年龄:20");
write.flush();
}
}
其中我把那个获取XMLHttpRequest对象的方法我封装到了一个js文件。
util.js封装文件代码如下:
/**
* 得到XMLHttpRequest对象
*/
function getXHR(){
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest();
}catch(e)
{
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("你的浏览器不支持ajax");
return false;
}
}
}
return xmlHttp;
}