1 ajax-lib/ajaxutils.js:
2
3 // 创建request对象
4 function createXMLHttpRequest() {
5 try {
6 return new XMLHttpRequest();//大多数浏览器
7 } catch (e) {
8 try {
9 return ActvieXObject("Msxml2.XMLHTTP");//IE6.0
10 } catch (e) {
11 try {
12 return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本
13 } catch (e) {
14 alert("哥们儿,您用的是什么浏览器啊?");
15 throw e;
16 }
17 }
18 }
19 }
20 /*
21 * option对象有如下属性
22 */
23 /* 请求方式method,
24 /* 请求的url url,
25 /* 是 否异步asyn,
26 /* 请求体params,
27 /* 回调方法callback,
28 /* 服务器响应数据转换成什么类型type
29 */
30 function ajax(option) {
31 /*
32 * 1. 得到xmlHttp
33 */
34 var xmlHttp = createXMLHttpRequest();
35 /*
36 * 2. 打开连接
37 */
38 if(!option.method) {//默认为GET请求
39 option.method = "GET";
40 }
41 if(option.asyn == undefined) {//默认为异步处理
42 option.asyn = true;
43 }
44 xmlHttp.open(option.method, option.url, option.asyn);
45 /*
46 * 3. 判断是否为POST
47 */
48 if("POST" == option.method) {
49 xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
50 }
51 /*
52 * 4. 发送请求
53 */
54 xmlHttp.send(option.params);
55
56 /*
57 * 5. 注册监听
58 */
59 xmlHttp.onreadystatechange = function() {
60 if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {//双重判断
61 var data;
62 // 获取服务器的响应数据,进行转换!
63 if(!option.type) {//如果type没有赋值,那么默认为文本
64 data = xmlHttp.responseText;
65 } else if(option.type == "xml") {
66 data = xmlHttp.responseXML;
67 } else if(option.type == "text") {
68 data = xmlHttp.responseText;
69 } else if(option.type == "json") {
70 var text = xmlHttp.responseText;
71 data = eval("(" + text + ")");
72 }
73
74 // 调用回调方法
75 option.callback(data);
76 }
77 };
78 };
79
80
81
82
83
84 servlet:
85 public void doGet(HttpServletRequest request, HttpServletResponse response)
86 throws ServletException, IOException {
87
88 String str = "{\"name\":\"zhangSan\", \"age\":189999, \"sex\":\"male\"}";
89 response.getWriter().print(str);
90 System.out.println(str);
91 }
92
93 使用:
94 <script type="text/javascript">
95 window.onload = function() {
96 var btn = document.getElementById("btn");
97 btn.onclick = function() {
98 ajax(
99 {
100 url : "<c:url value ='/Aservlet'/>",
101 type : "json",
102 callback : function(data) {
103 document.getElementById("h3").innerHTML = data.name +","
104 + data.age + "," + data.sex;
105 }
106 }
107 );
108 };
109 };
110 </script>
111 </head>
112 <body>
113 <button id="btn">点击这里</button>
114 <h1>显示自己的ajax小工具</h1>
115 <h3 id="h3"></h3>
116 </body>