Ajax原生请求和java对象转成json
\黑马程序员_超全面的JavaWeb视频教程vedio\黑马程序员_超全面的JavaWeb教程-源码笔记\JavaWeb视频教程_day23-资料源码\ajax_code\day23_3
本代码中有模拟 jquery里面的对Ajax的简化封装:
json2.jsp Ajax原生请求
<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%> <%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'json2.jsp' starting page</title> <metahttp-equiv="pragma"content="no-cache"> <metahttp-equiv="cache-control"content="no-cache"> <metahttp-equiv="expires"content="0"> <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"> <metahttp-equiv="description"content="This is my page"> <!--<link rel="stylesheet" type="text/css" href="styles.css">--> <scripttype="text/javascript"> functioncreateXMLHttpRequest() {try{return newXMLHttpRequest();//大多数浏览器 }catch(e) {try{returnActvieXObject("Msxml2.XMLHTTP");//IE6.0 }catch(e) {try{returnActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本 }catch(e) {
alert("哥们儿,您用的是什么浏览器啊?");throwe;
}
}
}
}
window.onload= function() {//获取btn元素 varbtn=document.getElementById("btn");
btn.onclick= function() {//给按钮的点击事件上添加监听 //使用ajax得到服务器端响应,把结果显示到h3中 //1. 得到request varxmlHttp=createXMLHttpRequest();//2. 连接 xmlHttp.open("GET","<c:url value='/AServlet'/>",true);//3. 发送 xmlHttp.send(null);//4. 给xmlHttp的状态改变事件上添加监听 xmlHttp.onreadystatechange= function() {//双重判断 if(xmlHttp.readyState== 4 &&xmlHttp.status== 200) {vartext=xmlHttp.responseText;//它是一个json串 //执行json串 varperson=eval("(" +text+ ")");vars=person.name+ "," +person.age+ "," +person.sex;
document.getElementById("h3").innerHTML=s;
}
};
};
};</script> </head> <body> <%--点击按钮后,把服务器响应的数据显示到h3元素中--%> <buttonid="btn">点击这里</button> <h1>JSON之Hello World</h1> <h3id="h3"></h3> </body> </html>
packagecn.itcast.demo1;importjava.util.ArrayList;importjava.util.List;importnet.sf.json.JSONArray;importnet.sf.json.JSONObject;importorg.junit.Test;/*** 演示JSON-LIB小工具
*@authorcxf
**/ public classDemo1 {/** 当map来用*/@Testpublic voidfun1() {
JSONObject map= newJSONObject();
map.put("name", "zhangSan");
map.put("age", 23);
map.put("sex", "male");
String s=map.toString();
System.out.println(s);
}/** 当你已经有一个Person对象时,可以把Person转换成JSONObject对象*/@Testpublic voidfun2() {
Person p= new Person("liSi", 32, "female");//把对象转换成JSONObject类型 JSONObject map =JSONObject.fromObject(p);
System.out.println(map.toString());
}/*** JSONArray*/@Testpublic voidfun3() {
Person p1= new Person("zhangSan", 23, "male");
Person p2= new Person("liSi", 32, "female");
JSONArray list= newJSONArray();
list.add(p1);
list.add(p2);
System.out.println(list.toString());
}/*** 原来就有一个List,我们需要把List转换成JSONArray*/@Testpublic voidfun4() {
Person p1= new Person("zhangSan", 23, "male");
Person p2= new Person("liSi", 32, "female");
List<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
System.out.println(JSONArray.fromObject(list).toString());
}
}
//创建request对象 functioncreateXMLHttpRequest() {try{return new XMLHttpRequest();//大多数浏览器 } catch(e) {try{return ActvieXObject("Msxml2.XMLHTTP");//IE6.0 } catch(e) {try{return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本 } catch(e) {
alert("哥们儿,您用的是什么浏览器啊?");throwe;
}
}
}
}/** option对象有如下属性*/ /*请求方式*/method,/*请求的url*/url,/*是否异步*/asyn,/*请求体*/params,/*回调方法*/callback,/*服务器响应数据转换成什么类型*/typefunctionajax(option) {/** 1. 得到xmlHttp*/ var xmlHttp =createXMLHttpRequest();/** 2. 打开连接*/ if(!option.method) {//默认为GET请求 option.method = "GET";
}if(option.asyn == undefined) {//默认为异步处理 option.asyn = true;
}
xmlHttp.open(option.method, option.url, option.asyn);/** 3. 判断是否为POST*/ if("POST" ==option.method) {
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}/** 4. 发送请求*/xmlHttp.send(option.params);/** 5. 注册监听*/xmlHttp.onreadystatechange= function() {if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {//双重判断 vardata;//获取服务器的响应数据,进行转换! if(!option.type) {//如果type没有赋值,那么默认为文本 data =xmlHttp.responseText;
}else if(option.type == "xml") {
data=xmlHttp.responseXML;
}else if(option.type == "text") {
data=xmlHttp.responseText;
}else if(option.type == "json") {var text =xmlHttp.responseText;
data= eval("(" + text + ")");
}//调用回调方法 option.callback(data);
}
};
};
ajaxutils.js
<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%> <%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'json3.jsp' starting page</title> <metahttp-equiv="pragma"content="no-cache"> <metahttp-equiv="cache-control"content="no-cache"> <metahttp-equiv="expires"content="0"> <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"> <metahttp-equiv="description"content="This is my page"> <!--<link rel="stylesheet" type="text/css" href="styles.css">--> <scripttype="text/javascript"src="<c:url value='/ajax-lib/ajaxutils.js'/>"></script> <scripttype="text/javascript">window.onload= function() {varbtn=document.getElementById("btn");
btn.onclick= function() {/*1. ajax*/ajax(
{
url:"<c:url value='/AServlet'/>",
type:"json",
callback:function(data) {
document.getElementById("h3").innerHTML=data.name+ "," +data.age+ "," +data.sex;
}
}
);
};
};</script> </head> <body> <%--点击按钮后,把服务器响应的数据显示到h3元素中--%> <buttonid="btn">点击这里</button> <h1>显示自己封装的ajax小工具</h1> <h3id="h3"></h3> </body> </html>
json3.jsp 调用简化的Ajax