JavaScript Ajax编程 应用篇

内容摘要
一、Ajax (Asynchronous JavaScript + XML) 能够像服务器请求额外的数据而无需卸载页面,即局部刷新技术

二、创建一个XHR对象




function createXHR () {
if (typeof
文章正文

一、Ajax  (Asynchronous JavaScript + XML)  能够像服务器请求额外的数据而无需卸载页面,即局部刷新技术
二、创建一个XHR对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function createXHR () {
if (typeof XMLHttpRequest != "undefined") {
 return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") { // < Ie7
 if (typeof arguments.callee.activeXString != "string") {
 var version = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"],
  i, len;
 for ( i = 0, len = version.length; i < len; i++) {
  try {
  new ActiveXObject(version[i]);
  arguments.callee.activeXString = version[i];
  break;
  } catch (ex) {}
 }
 }
 return new ActiveXObject(arguments.callee.activeXString);
} else {
 throw new Error("No Support For XHR");
}
}
var xhr = createXHR();
alert(xhr); // [object XMLHttpRequest]

三、用法    注意:本节的实例都应用于服务器端
    1.调用open()方法。它接受3 个参数:要发送的请求的类型("get"、"post"等)、请求的URL 和表示是否异步发送请求的布尔值。
    2.要发送请求,调用send()方法,接受一个参数,即要作为请求发送的主体。如果不需要,则为null
    3.返回的数据会自动填充到XHR对象的属性中。   

1
2
3
4
5
6
7
8
9
10
11
12
var xhr = createXHR();
// GET方式同步打开example.txt文件
// 同步:javascript代码会等待服务器响应后执行
xhr.open("get", "example.txt", false);
xhr.send(null);
// status代表响应的http状态
// 200代表ok,304表示缓存
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
 alert(xhr.responseText); // 返回响应的文本,123456
} else {
 alert("Request was unsuccessful: " + xhr.status);
}

    4.example.text文件内容为字符串: 123456

四、前面的使用的同步的方式,当然不会存在问题,所有我们要挑战一个异步的方法。   

1
2
3
4
5
6
7
8
9
10
11
12
13
var xhr = createXHR();<br> // xhr.readyState表示请求/响应的当前状态,4代表已经接受了全部的响应数据
// 另外只要xhr.readyState的值发生了改变,那么xhr.onreadystatechange事件就会触发
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
 alert(xhr.responseText);
 } else {
 alert("Request was unsuccessful: " + xhr.status);
 }
}
};
xhr.open("get", "example.txt", true);
xhr.send(null);

五、每个HTTP 请求和响应都会带有相应的头部信息
    1.默认情况下,在发送XHR 请求的同时,还会发送下列头部信息。
        ①Accept:浏览器能够处理的内容类型。
        ②Accept-Charset:浏览器能够显示的字符集。
        ③Accept-Encoding:浏览器能够处理的压缩编码。
        ④Accept-Language:浏览器当前设置的语言。
        ⑤Connection:浏览器与服务器之间连接的类型。
        ⑥Cookie:当前页面设置的任何Cookie。
        ⑦Host:发出请求的页面所在的域。
        ⑧Referer:发出请求的页面的URI。
        ⑨User-Agent:浏览器的用户代理字符串。
    2.使用setRequestHeader()方法可以设置自定义的请求头部信息。接受两个参数:头部字段的名称和头部字段的值      

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var xhr = createXHR();
// xhr.readyState表示请求/响应的当前状态,4代表已经接受了全部的响应数据
// 另外只要xhr.readyState的值发生了改变,那么xhr.onreadystatechange事件就会触发
xhr.onreadystatechange = function(){
 if (xhr.readyState == 4){
 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
  alert(xhr.responseText);
 } else {
  alert("Request was unsuccessful: " + xhr.status);
 }
 }
};
xhr.open("get", "example.txt", true);
// 必须在open()之后调用
xhr.setRequestHeader("name", "zhang"); // 在example.txt的http中可以看到接受的 "name" : "zhang"
xhr.send(null);

    3.获取请求的头部信息和相应信息,调用getResponseHeader()方法getAllResponseHeaders()方法     

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var xhr = createXHR();
// xhr.readyState表示请求/响应的当前状态,4代表已经接受了全部的响应数据
// 另外只要xhr.readyState的值发生了改变,那么xhr.onreadystatechange事件就会触发
xhr.onreadystatechange = function(){
 if (xhr.readyState == 4){
 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
  // 获取响应头的Content-Type
  var connection = xhr.getResponseHeader("Content-Type");
  // alert(connection); // text/plain
  // 获取所有的响应信息
  var all = xhr.getAllResponseHeaders();
  alert(all);
 } else {
  alert("Request was unsuccessful: " + xhr.status);
 }
 }
};
xhr.open("get", "example.txt", true);
xhr.send(null);

六、GET请求,前面我们已经讨论了GET请求的方法,现在我们来扩展一下,为GET请求添加一些参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
url : 不带请求的url
name : 请求键
value : 请求值
return : 带请求字符串的url
*/
function addURLParam(url, name, value) {
url += (url.indexOf("?") == -1 ? "?" : "&");
url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
return url;
}
var xhr = createXHR();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
 alert(xhr.responseText);
 } else {
 alert("Request was unsuccessful: " + xhr.status);
 }
}
};
var url = "example.txt";
url = addURLParam(url, "name", "zhang");
url = addURLParam(url, "age", "23");
// 请求的url变成了:example.txt?name=zhang&age=23
xhr.open("get", url, true);
xhr.send(null);

七、POST请求
    1.案例分析:接下来我们共同讨论一个以post方法发送请求的ajax应用,即用户注册,根据你注册用户名返回提示。
    2.实现步骤
        1) 首先要有一个注册的页面(当然,这里很简陋)ajax.html         

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE HTML>
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title>无标题文档</title>
 <style>
 </style>
 </head>
 <body>
 <form name="myForm" method="post">
 姓名:<input type="text" name="username" /><label id="userLabel">请输入用户名</label><br/>
 密码:<input type="password" name="password" /><br/>
  <input type="submit" value="登录" /><br/>
 </form>
 <script src="EventUtil.js"></script>
 <script src="serialize.js"></script>
 <script src="ajax.js"></script>
 <script src="ajaxDo.js"></script>
 </body>
 </html>

        2) 接着当然是javascript部分
            ①EventUtil.js,这里只是将事件监听的部分列出来              

1
2
3
4
5
6
7
8
9
10
11
var EventUtil = {
  addEvent : function (element, type, handler) {
  if (element.addEventListener)
  {
   element.addEventListener(type, handler, false);
  } else if (element.attachEvent)
  {
   element.attachEvent("on" + type, handler);
  }
  }
 }

            ②serialize.js:表单序列化            

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function serialize(form){
  var parts = [], field = null, i, len, j, optLen, option, optValue;
  for (i=0, len=form.elements.length; i < len; i++){
  field = form.elements[i];
  switch(field.type){
   case "select-one":
   case "select-multiple":
   if (field.name.length){
   for (j=0, optLen = field.options.length; j < optLen; j++){
    option = field.options[j];
    if (option.selected){
    optValue = "";
    if (option.hasAttribute){
     optValue = (option.hasAttribute("value") ?
     option.value : option.text);
    } else {
     optValue = (option.attributes["value"].specified ?
     option.value : option.text);
    }
    parts.push(encodeURIComponent(field.name) + "=" +
    encodeURIComponent(optValue));
    }
   }
   }
   break;
   case undefined: //字段集
   case "file": //文件输入
   case "submit": //提交按钮
   case "reset": //重置按钮
   case "button": //自定义按钮
   break;
   case "radio": //单选按钮
   case "checkbox": //复选框
   if (!field.checked){
   break;
   }
   /* 执行默认操作*/
   default:
   //不包含没有名字的表单字段
   if (field.name.length){
    parts.push(encodeURIComponent(field.name) + "=" +
    encodeURIComponent(field.value));
   }
  }
  }
  return parts.join("&");
 }

            ③ajax.js,就是上面的那个createXHR()函数,这里就不罗列了。
            ④ajaxDo.js,核心文件,就是我们操作部分,这个名字乱写的。
              

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var form = document.forms[0]; // 获取表单
 var username = form.elements['username']; // 用户名
 var userLabel = document.querySelector("#userLabel"); // 提示标签
 EventUtil.addEvent(username, "blur", function() {
  var xhr = createXHR();
  xhr.onreadystatechange = function(){
  if (xhr.readyState == 4){
   if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
   var text = xhr.responseText;
   // 当为true时,提示绿色字体
   // 当为false时,提示为红色字体
   if(text) {
    userLabel.style.color = "green";
    userLabel.firstChild.data = "恭喜你,用户名可用";
   } else {
    userLabel.style.color = "red";
    userLabel.firstChild.data = "对不起,该用户已存在";
   }
   } else {
   alert("Request was unsuccessful: " + xhr.status);
   }
  }
  };
  // POST请求
  xhr.open("post", "dome.php", true);
  // 提交的内容类型
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  // 将表单序列化
  xhr.send(serialize(form));
 });

    3.改进部分:大家都看见了,刚才在提交表单时,我们序列化了表单。在XMLHttpRequest 2 级为此定义了FormData 类型,它会自动为我们序列化表单,不需要我们自己写了。
        我们只动部分代码       

1
2
3
4
5
// ...此处省略代码和上面一致
// POST请求
xhr.open("post", "dome.php", true);
// 仅仅这里需要改动,代替之前serialize.js中的函数
xhr.send(new FormData(form));

八、其他部分(了解,因为兼容性还不够)
    1.超时设定      

1
2
3
4
5
6
xhr.open("get", "example.txt", true);
xhr.timeout = 1000; //将超时设置为1 秒钟(仅适用于IE8+)
xhr.ontimeout = function(){
alert("Request did not return in a second.");
};
xhr.send(null);

    2.overrideMimeType()方法,针对服务器返回的类型  

1
2
3
4
var xhr = createXHR();
xhr.open("get", "example.txt", true);
xhr.overrideMimeType("text/xml"); // 之前的是text/plain
xhr.send(null);

    3.进度事件
        1.load事件,只要浏览器收到服务器的信息就触发     

1
2
3
4
5
6
7
8
9
10
var xhr = createXHR();
 xhr.onload = function(){
 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
  alert(xhr.responseText);
 } else {
  alert("Request was unsuccessful: " + xhr.status);
 }
 };
 xhr.open("get", "example.txt", true);
 xhr.send(null);

        2.progress事件,浏览器接收新数据期间周期性地触发         

1
2
3
4
5
6
7
8
9
10
11
var xhr = createXHR();
 xhr.onprogress = function(event){
 var divStatus = document.getElementById("status");
 // 计算从响应中已经接收到的数据的百分比
 if (event.lengthComputable){
  divStatus.innerHTML = "Received " + event.position + " of " +
  event.totalSize +" bytes";
 }
 };
 xhr.open("get", "altevents.php", true);
 xhr.send(null);

以上就是本文的全部内容,希望对大家的学习有所帮助。


代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!