Ajax学习

Ajax是对Asynchronous JavaScript + XML的简写。
Ajax是一种无需刷新页面就能够从服务器取得数据的方法(机制)。
负责Ajax运作的核心对象是XMLHttpRequest(XHR)对象。

1、创建XMLHttpRequest对象

<span style="font-size:18px;">function createXHR() {
	if (typeof XMLHttpRequest != "undefined") {
		return new XMLHttpRequest();
	} else if (typeof ActiveXObject != "undefined") {
		if (typeof arguements.callee.ActiveXString != "string") {
			var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"];
			var i, len; 
			for (i = 0, len = versions.length; i < length; i++) {
				try {
					new ActiveXObject(versions[i]);
					arguements.callee.ActiveXString = versions[i];
					break;
				} catch (ex) {
					//
				}
			}
		}
	} else {
		throw new Error("No XHR object available.");
	}
}</span>

2、使用XHR
1)同步使用XHR

<span style="font-size:18px;">var xhr = createXHR();
xhr.open("get", "example.txt", false);
xhr.send(null);

if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
	alert(xhr.responseText);
} else {
	alter("Request was unsuccessful: " + xhr.status);
}</span>
2)异步使用XHR
<span style="font-size:18px;">var xhr = createXHR();
// readyState值改变时会触发
xhr.onreadystatechange = function() {
	if (xhr.readyState == 4) {
		if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
			alert(xhr.responseText);
		} else {
			alter("Request was unsuccessful: " + xhr.status);
		}	
	}
	
};

xhr.open("get", "example.txt", true);
xhr.setRequestHeader("MyHeader", "MyValue"); //
xhr.send(null);</span>
3)GET请求
<span style="font-size:18px;">xhr.open("get", "example.php?name1=value1&name2=value2", true);
// 加入参数
function addURLParam(url, name, value) {
	url += (url.indexOf("?") == -1 ? "?" : "&");
	url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
	return url;
}

url = addURLParam(url, "name", "jxt");</span>
4)POST 请求
<span style="font-size:18px;">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 {
				alter("Request was unsuccessful: " + xhr.status);
			}	
		}	
	;

	xhr.open("post", "example.txt", true);
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //
	var form = document.getElementById("user-info");
	xhr.send(serialize(form));
}</span>
3、XMLHttpRequest 2
1)超时设置

<span style="font-size:18px;">var xhr = createXHR(); 
xhr.onreadystatechange = function() { 
	if (xhr.readyState == 4) { 
		try { 
			if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ 
				alert(xhr.responseText); 
			} else { 
				alert("Request was unsuccessful: " + xhr.status); 
			} 
		} catch (ex) { 
		//假设由ontimeout事件处理程序处理
		} 
	} 
}; 

xhr.open("get", "timeout.php", true); 
xhr.timeout = 1000; //将超时设置为1秒钟(仅适用于IE8+)
xhr.ontimeout = function(){ 
	alert("Request did not return in a second."); 
}; 
xhr.send(null); </span>
4、进度事件
<span style="font-size:18px;">// load:在接收到完整的响应数据时触发。
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", "altevents.php", true); 
xhr.send(null);

// progress:在接收响应期间持续不断地触发。
var xhr = createXHR(); 
xhr.onload = function(event) { 
	if ((xhr.status >= 200 && xhr.status < 300) || 
		xhr.status == 304){ 
		alert(xhr.responseText); 
	} else { 
		alert("Request was unsuccessful: " + xhr.status); 
	} 
}; 
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);</span>
同源策略是对XHR的一个主要约束,它为通信设置了“相同的域、相同的端口、相同的协议”这一限制。试图访问上述限制之外的资源,都会引发安全错误,除非采用被认可的跨域解决方案。CORS(Cross-Origin Resource Sharing,跨源资源共享)是W3C的一个工作草案,定义了在必须访问跨源资源时,浏览器与服务器应该如何沟通。CORS背后的基本思想,就是使用自定义的HTTP头部让浏览器与服务器进行沟通,从而决定请求或响应是应该成功,还是应该失败。

参考:《JavaScript高级程序设计》








你可能感兴趣的:(Ajax学习)