AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
注意,Ajax只能接收后端即servlet传来的打印流数据——printWrite,不能获取servlet作用域对象里的数据
通过在后台与服务器进行少量数据交换,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();
}
}
}
<%@ 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 = ""+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>
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-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_23display-name>
<servlet>
<servlet-name>Helloservlet-name>
<servlet-class>com.coolr.ajax.Helloservlet-class>
servlet>
<servlet-mapping>
<servlet-name>Helloservlet-name>
<url-pattern>/Hellourl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.htmwelcome-file>
<welcome-file>index.jspwelcome-file>
<welcome-file>default.htmlwelcome-file>
<welcome-file>default.htmwelcome-file>
<welcome-file>default.jspwelcome-file>
welcome-file-list>
web-app>
把需要自定义传入的形参改为对象。对象的好处是,对象.操作可以直接生成对象,也可以作为获取使用,在自封装的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);
}
}
}