自定义封装 Ajax 方法——并调用

Ajax 是什么

AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
注意,Ajax只能接收后端即servlet传来的打印流数据——printWrite,不能获取servlet作用域对象里的数据

  1. Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
  2. Ajax = 异步 JavaScript 和 XML 或者是 HTML(标准通用标记语言的子集)。
  3. Ajax 是一种用于创建快速动态网页的技术。
  4. Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
  5. Ajax技术核心是XMLHttpRequest对象(简称XHR),它是一门与服务端进行数据交换的技术。

通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

自定义封装Ajax代码

放入WebRoot下的自定义文件夹内,文件名取为MyAjax.js

/**
 * @author Cool.R
 * @since 2019-08
 * 
 * @param type传输方式 get 或 post  默认get
 * @param url目标路径
 * @param sync是否启用异步 默认启动异步
 * @param data  需要传输的参数 格式 “ name1=value1&name2=value2 ” 等等
 * @param sucess  服务器成功相应后的操作 自定义函数
 * @param noFound  请求页面无法获取时的操作 自定义函数
 * @param error   服务器内部错误时的操作 自定义函数
 * @param loading  页面成功加载前的相应 自定义函数
 */
function myAjax(type, url, sync, data, success, noFound, error, loading) {
	if (type == null) {
		type = "get";
	}
	if (sync == null) {
		sync = true;
	}
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {  /* onreadystatechange 事件是用来检测readyState值的变化
	 										readyState的值每变化一次,onreadystatechange事件就会被触发,从而运行其绑定的函数
	 										readyState值的范围是0、1、2、3、4,当readyState==4表示请求得到相应并成功*/
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {    /* status值是服务器返回的HTTP状态码,200代表成功,404代表所请求的页面未找到 500表示服务器内部错误					*/
				success(xhr);
			} else if (xhr.status == 404) {
				noFound(xhr);
			} else if (xhr.status == 500) {
				error(xhr);
			}
		} else {
			loading(xhr);
		}
	}
	if (type.toLowerCase() == "get") {
		if (data == null) {
			xhr.open(type, url + data, sync);
			xhr.send();
		} else {
			xhr.open(type, url + "?" + data, sync);
			xhr.send();
		}
	}
	if (type.toLowerCase() == "post") {
		if (data == null) {
			xhr.open(type, url, async)
			xhr.setRequestHeader("content-type",
					"application/x-www-form-urlencoded");
			xhr.send(data);
		} else {
			xhr.open(type, url, async)
			xhr.setRequestHeader("content-type",
					"application/x-www-form-urlencoded");
			xhr.send();
		}
	}
}

调用自定义Ajax

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'MyAjax.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script src="Ajax/myAjax.js"></script>
<script type="text/javascript">
	/* 	function myAjax(method,url,sync,data,sucess,noFound,error,loading){
	 if(sync==null){
	 sync=true;
	 }
	 var xhr=new XMLHttpRequest();
	 xhr.onreadystatechange=function(){
	 if(xhr.readyState==4){
	 if(xhr.status==200){
	 sucess();
	 }else if(xhr.status==404){
	 noFound();
	 }else if(xhr.status==500){
	 error();
	 }
	 }else{
	 loading();
	 }
	 }
	 if(method.toLowerCase() == "get"){
	 xhr.open(method,url+"?"+data,sync);
	 xhr.send();
	 }
	 if(method.toLowerCase() == "post"){
	 xhr.open(method, url, async)
	 xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
	 xhr.send(data);
	 }
	 } */
	/*
	function egAjax(){
		var xhr=new XMLHttpRequest();
		xhr.onreadystatechange=function(){
			if(xhr.readyState==4){
				if(xhr.status==200){
					//成功
				}else if(xhr.status==404){
					//未找到
				}else if(xhr.status4==500){
					//服务器抢修中
				}
			}else{
				//努力加载中
			}
		}
		
		
		xhr.open("post", "Hello", true);
		xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
		xhr.send();
	} */
	/* 自定义success   noFound   error  loading  相应函数 */
	var sucess = function(xhr) {
		document.getElementById("dv1").innerHTML = "<img src='timg.gif' />"+xhr.responseText;
	}
	var noFound = function(xhr) {

		document.getElementById("dv1").innerHTML = "NoFound!";
	}

	var error = function(xhr) {

		document.getElementById("dv1").innerHTML = "错误!!!";
	}

	var loading = function(xhr) {

		document.getElementById("dv1").innerHTML = "加载中.......";
	}
	
	/* 調用自定义封装的的Ajax方法 */
	function test(){
	myAjax("get", "Hello", true, "name=齐天大圣&age=25", sucess, noFound, error,
			loading);
}
</script>

<style type="text/css">
#dv1 {
	width: 900px;
	height: 200px;
	border: 1px solid red;
	vertial-align: middle;
	text-align: center;
	line-height: 200px;
	background-color: skyblue;
}
#dv1 img {
	height:200px;
	line-height: 200px;
	opcatiy: 0.5;
	
}
</style>
</head>

<body>
	<button onclick="test()">测试</button>
	<div id="dv1"></div>
</body>
</html>

进行逻辑处理的servlet

package com.coolr.ajax;

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

import javax.lang.model.element.VariableElement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Hello 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 {
		//设置接收字符集
		request.setCharacterEncoding("utf-8");
		//设置响应字符集
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.write("你好,新数据!");
		String name= request.getParameter("name");
		String age=request.getParameter("age");
		System.out.println(name+"\n"+age);
		out.write(name+"\n"+age);
	}

}

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Ajax8_23</display-name>
  <servlet>
    <servlet-name>Hello</servlet-name>
    <servlet-class>com.coolr.ajax.Hello</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/Hello</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

效果

点击测试按钮在这里插入图片描述

线程模拟睡眠5秒在这里插入图片描述

自定义Ajax封装优化

把需要自定义传入的形参改为对象。对象的好处是,对象.操作可以直接生成对象,也可以作为获取使用,在自封装的Ajax方法的形参列表写一个obj即可,使自定义封装的Ajax函数更简单,而且不需要填入非必须的参数。

/**
 * @author Cool.R
 * @see 2019-08
 * @param obj
 *            传入各种对象 {type:"get"} ,{success:function(){xxxxx}}等形式传入参数
 */
function myAjax(obj) {
	if (obj.type == null) {
		obj.type = "get";
	}
	if (obj.sync == null) {
		obj.sync = true;
	}
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				obj.success(xhr);
			} else if (xhr.status == 404) {
				obj.noFound(xhr);
			} else if (xhr.status == 500) {
				obj.error(xhr);
			}
		} else {
			obj.loading(xhr);
		}
	}
	if (obj.type.toLowerCase() == "get") {
		if (data != null) {
			xhr.open(obj.type, obj.url + "?" + obj.data, obj.sync);
			xhr.send();
		} else {
			xhr.open(obj.type, obj.url + "?" + obj.data, obj.sync);
			xhr.send();
		}
	}
	if (obj.type.toLowerCase() == "post") {
		if (data != null) {
			xhr.open(obj.type, obj.url, obj.async)
			xhr.setRequestHeader("content-type",
					"application/x-www-form-urlencoded");
			xhr.send(obj.data);
		} else {
			xhr.open(obj.type, obj.url, obj.async)
			xhr.setRequestHeader("content-type",
					"application/x-www-form-urlencoded");
			xhr.send(obj.data);
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值