Ajax的封装以及与java代码的数据传输

JSP文件代码

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




Insert title here







JS文件代码(ajax的封装)

//type, url, async, param, handler200,handler404,handler500,loading
// 将相同的留下来,将不同的作为参数传递
function ajax(obj) {
	if(obj.type == null){
		obj.type = "get";
	}
	
	if (obj.async == null) {
		obj.async = true; // 默认使用异步
	}
	var xhr = new XMLHttpRequest();

	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				obj.handler200(xhr);
			} else if (xhr.status == 404) {
				if(obj.handler404 != null){
					obj.handler404(xhr);
				}
			} else if (xhr.status == 500) {
				if(obj.handler500 != null){
					obj.handler500(xhr);
				}
			}
		} else {
			if(obj.loading != null){
				obj.loading(xhr);
			}
		}
	}

	if (obj.type.toLowerCase() == "get") {
		if (obj.param != null) {
			xhr.open(obj.type, obj.url + "?" + obj.param, obj.async);
		} else {
			xhr.open(obj.type, obj.url, obj.async);
		}
		xhr.send();
	} else if (obj.type.toLowerCase() == "post") {
		xhr.open(obj.type, obj.url, obj.async);
		xhr.setRequestHeader("content-type",
				"application/x-www-form-urlencoded");
		xhr.send(obj.param);
	}
}

Servlet文件代码的传输

package cn.test.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GetDateServlet
 */
@WebServlet("/getdata")
public class GetDateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(request.getParameter("name"));
		System.out.println(request.getParameter("age"));
		PrintWriter out = response.getWriter();
		out.write("{\"name\":\"zhangsan\",\"age\":18}");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

你可能感兴趣的:(后端服务器)