1. 程式人生 > >純js的ajax和Java後臺互動

純js的ajax和Java後臺互動

今天用了純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.onload=function(){
	document.getElementById("btn1").onclick=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;
}