纯js的ajax和Java后台交互

今天用了纯js代码写ajax和后台交互,写好了最开始没得问题,但是前端接收后台数据的时候遇到问题了。一直获取不到值,原来是我理解错了,获取后台的相关操作必须写到那个状态变化监听器里面。也就是需要写到onreadystatechange里面。最开始我一直以为获取后台的操作应该在发送请求(send)之后。弄了很久,最后还是一同学帮我看到了错误。

前台代码为:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>





ajax学习





后台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("我是输出的文字
"); write.println("姓名:花2不谢
年龄: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;
}


你可能感兴趣的:(Java,web前端,ajax)