<%@ 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 'fzajax.jsp' starting page</title>
<script src="js/ajaxutil.js"></script>
<script type="text/javascript">
/* ajax(null, "hiservlet", null, null, function(data) {
document.getElementById("myDiv").innerHTML = data.responseText;
}); */
//创建json格式的对象
var obj = {key:"value",username:"zhangsan",age:18}
console.log(obj.username)
//调用封装2.0的方法
ajax({
url : "hiservlet",
handler200 : function(data) {
document.getElementById("myDiv").innerHTML = data.responseText;
}
});
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
//封装2.0
//将所有的参数封装到一个对象中
//method, url, data, async,handler200,hanlder404,handler500,loading
function ajax(obj) {
if (obj.method == null) {
obj.method = "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.hanlder404 != null){
obj.hanlder404(xhr);
}
} else if (xhr.status == 500) {
if(obj.handler500 != null){
obj.handler500(xhr);
}
}
} else {
if(obj.loading != null){
obj.loading(xhr);
}
}
}
if (obj.method.toUpperCase() == "GET") {
if (obj.data != null) {
xhr.open(obj.method, obj.url + "?" + obj.data, obj.async)
} else {
xhr.open(obj.method, obj.url, obj.async)
}
xhr.send();
} else if (obj.method.toUpperCase() == "POST") {
xhr.open(obj.method, obj.url, obj.async)
xhr.setRequestHeader("content-type",
"application/x-www-form-urlencoded");
xhr.send(obj.data);
}
}
//old封装1.0
/*function ajax(method, url, data, async,handler200,hanlder404,handler500,loading) {
if (method == null) {
method = "GET";
}
if(async == null){
async = true;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
handler200(xhr);
} else if (xhr.status == 404) {
if(hanlder404 != null){
hanlder404(xhr);
}
} else if (xhr.status == 500) {
if(handler500 != null){
handler500(xhr);
}
}
} else {
if(loading != null){
loading(xhr);
}
}
}
if (method.toUpperCase() == "GET") {
if (data != null) {
xhr.open(method, url + "?" + data, async)
} else {
xhr.open(method, url, async)
}
xhr.send();
} else if (method.toUpperCase() == "POST") {
xhr.open(method, url, async)
xhr.setRequestHeader("content-type",
"application/x-www-form-urlencoded");
xhr.send(data);
}
}*/