Ajax
AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
简单的说就是只更新你要更新的部分。
ajax的核心就是XMLHttpRequest 对象 这个对象就像是浏览器与服务器之间的中间人,js可以通过这个对象发送请求 也可以处理响应。
首先创建一个例子,保存为Ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>
<div id="new"></div>
<script src="js/addLoadEvent.js"></script>
<script src="js/getHTTPObject.js"></script>
<script src="js/getNewContent.js"></script>
</body>
</html>
其中的addLoadEvent.js,getHTTPObject.js,getNewContent.js 位于项目中的js文件夹(自己创建)。与 ajax.html并列的的文件example.txt(自己创建 随便打几个文字)。
下面编写addLoadEvent.js 主要功能就是在页面加载玩执行函数 (只有一个参数 要执行的函数)可以多次使用。
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}else{
window.onload = function (argument) {
oldonload();
func();
}
}
}
编写getHTTPObject.js 。创建 XMLHttpRequest对象 。兼容了不同的浏览器
function getHTTPObject() {
if (typeof XMLHttpRequest == 'undefined') {
XMLHttpRequest = function(){
try{
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
}catch(e){}
try{
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
}catch(e){}
try{
return new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){}
return false;
}
}
return new XMLHttpRequest();
}
处理响应 getNewContent.js
function getNewContent() {
var request = getHTTPObject();
if (request) {
request.open("GET","example.txt",true);
request.onreadystatechange = function () {
if (request.readyState == 4) {
alert("revice");
var para = document.createElement("p");
var txt = document.createTextNode(request.responseText);
para.appendChild(txt);
document.getElementById('new').appendChild(para);
}
};
request.send(null);
}else{
alert("不行");
}
alert("fundone");
}
addLoadEvent(getNewContent);
得到以下的内容
注意
1, 在使用 Ajax 时一定要注意 同源策略,使用XMLHttpRequset 对象发送的请求只能访问html同一个域的数据 不能向其他的域发送请求。
2,有些浏览器会限制Ajax请求使用的协议 在chrome中用 file://协议从自己的硬盘中访问数据 就会看见如下图的错误提示。
Failed to load xxx Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https
=======================================================
Hijax 渐进增强的Ajax
就是拦截用户的请求,在没有Ajax的情况下仍能完成请求与响应 而不是中断。
具体的等我看到再添加。。。