javascript高级程序设计--Ajax总结

AJAX与COMENT

21.1 XMLHttpRequest对象

如果需要根据库的情况创建最新版本的XHR对象 可以在for循环中嵌套try catch

function createXHR(){
	if (typeof XHLHttpRequest != "undefined"){
        return new XMLHttpRequest();
    }else if(type of ActiveXobject != "undefined"){
        if(typeof arguments.callee.activeXString != "string"){
        	var versions ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],
            	i,len;
       	for (i=0,len=versions.length;i<len;i++){
            try{
				new ActiveXObject(version[i]);
                arguements.callee.activeXString = version[i];
                break;
            }catch(ex){
                //跳过
            }
        }
     }
	return new ActiveXObject(arguments.callee.activeXSring);
    }else{
        throw new Error("No XHR object available.");
    }
}

这个函数首先检测原生XHR对象是否存在,如果存在则返回它的新实例。如果原生对象不存在。则检测ActixeX对象。如果两种都不存在,就抛出一个错误。然后就可以使用下列代码在所有的浏览器中创建XHR对象了。

var xhr = createXHR();

21.1.1 XHR用法

使用XHR对象要调用的第一个方法就是open() 三个参数:get/post,url, 是否异步布尔值

调用open()还不会发送请求,还必修调用**第二个方法Send()**返回,如果不需要发送数据则send(null)

这个请求是同步的,相应的数据会自动填充到XHR对象的属性,相关属性如下:

responseText:作为相应的主体被返回的文本

responseXML: 如果相应的内容类型是"text/xml"或"application/xml",这个属性中将保存包含着响应数据的XML DOM文档

status :响应的HTTP的状态(200 304 502……)

statusText :HTTP状态的说明

xhr.open("get","example.txt",false);//false代表同步
xhr.send(null);
if((xhr.status >= 200 && xhr.status < 300)|| xhr.status==304){
	alert(xhr.responseText);
}else{
	alert("Request was unsuccesful:"+xhr.status);
}

readyState属性:0:未初始化,尚未调用open()

​ 1:启动 已经调用open() 但未调用Send()

​ 2:发送 已经调用send() 但尚未接收到响应

​ 3:接收 已经接收到部分响应数据

​ 4 完成 已经接收到全部响应数据,而且已经可以在客户端使用

//只要readySate属性的值改变,都会触发一次readyStatechange事件,可以用这个事件来检测每次状态的变化
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 unsuccesful:"+xhr.status);
		}
    }
};
xhr.open("get","example.txt",true);
xhr.send(null);

**第三个方法abort()**取消异步请求 调用这个方法会停止触发事件,而且再也不允许访问任何与响应有关的对象属性。

21.1.2 HTTP头部信息

每个http请求和响应都会带有响应的头部信息。

使用setRequestHeader()方法可以设置自定义的请求头部信息。两个参数头部字段的名称和头部字段的值。

必须在调用open和调用send之前

xhr.open("get","example.txt",true);
xhr.setRequestHeader("MyHeader","MyValue");
xhr.send(null);

调用getResponseHeader()方法传入头部字段的名称可以取得相应的相应头部信息。

调用getAllResponseHeader()方法通常会返回多行文本内容

21.1.3 GET请求

GET请求时最常见的请求类型,最常用于向服务器查询某些信息。必要时,可以将查询字符串参数追加到URL末尾,以便将信息发送到服务器。open方法的URL末尾的查询字符串必须经过正确编码:

xhr.open("get","example.php?name1=value1&name2=value2",true);
function addURLParam(url,name,value){
	url += (url.indexOf("?") == -1 ? "?" : "&");
	url += encodeURLComponent(name) +"=" +encodeURLComponent(value);
	return url;
}

var url = "example.php";
url = addURLParam(url,"name","Nicholas");
xhr.open("get",url,false);

21.1.4 POST请求

通常用于向服务器发送应该被保存的数据。POST请求的主体可以包含非常多的数据。

xhr.open("post"."example.php",true);

第二步就是在send方法中传入数据

模仿表单提交:

function submitData(){
	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 unsuccesful:"+xhr.status);
            }
        }
    };
    xhr.open("post"."example.php",true);
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //如果不设置头部信息则发送给服务器的数据就不会出现在$_POST超级全局变量中。
    var form = document.getElementById("user-info");
    xhr.send(serialize(form));
}

post请求的速度比get请求慢一倍

21.2 XMLHttpRequest 2级

21.2.1 FormData

2级定义了FormData类型 ,可以用append()方法,也可以document.forms[0]

var data = new FormData();
data.append("name","lucy");

var form = document.getElementById("user-info");

再用send(new FormData(form))把数据传输过去

21.2.2 超时设定

xhr.open("post"."example.php",true);
xhr.timeout =1000;
xhr.ontimeout = function(){
	alert("Request did not return in a second");
};
xhr.send(null);

XHR对象添加了一个timeout属性,表示请求再等待多少毫秒之后就会终止

(在超时之后访问readyState=4的话status也会报错)

21.2.3 overrideMimeType()方法

强制重写服务器返回的MIME类型,调用overrideMimeType()方法必须在send()方法之前

21.3 进度时间

21.3.1 load事件

响应接收完毕之后才触发load事件,所有没有必要去检查readyState属性了。

var xhr = createXHR();
xhr.onload = function(){
	    if((xhr.status >= 200 && xhr.status < 300)|| xhr.status==304){
            alert(xhr.responseText);
        }else{
            alert("Request was unsuccesful:"+xhr.status);
		}
};
xhr.open("get","example.txt",true);
xhr.send(null);

21.3.2 progress事件

这个事件会在浏览器接收新数据期间周期性的触发。必须在open方法之前添加onprogress事件。在下面例子中每次触发progress事件都会以新的状态信息更新HTML元素的内容。

var xhr = createXHR();
xhr.onload = function(){
	    if((xhr.status >= 200 && xhr.status < 300)|| xhr.status==304){
            alert(xhr.responseText);
        }else{
            alert("Request was unsuccesful:"+xhr.status);
		}
};
xhr.onprogress = function(event){
    var divStatus = document.getElementById("status");
    if (event.lengthComputable){
        divStatus.innerHTML = "Recieved" + event.position +"of" + event.totalSize + "bytes";
    }
}
xhr.open("get","example.txt",true);
xhr.send(null);

你可能感兴趣的:(js高级程序设计笔记,javascript,ajax)