目录
Ajax介绍
AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
有很多使用 AJAX 的应用程序案例:新浪微博、Google 地图、开心网等等。
Ajax创建
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
// GET方式
xhr.open('GET', 'url', 'true');
// 如果是POST方式,需要在send函数中申明数据格式
xhr.open('POST', 'url', 'true');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencode');
xhr.send();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
Ajax封装
var xhr = (function(){
var o = window.XMLHttpRequest ?
new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
if (!o) {
throw new Error('您的浏览器不支持异步请求HTTp');
}
function _doAjax(opt) {
var opt = opt || {},
type = (opt.type || 'GET').toUpperCase(),
async = opt.async || true,
url = opt.url,
data = opt.data || null,
error = opt.error || function(){},
success = opt.success || function(){},
complete = opt.complete || function(){};
if (!url) {
throw new Error('您没有输入URL');
}
o.open(type, url, async);
if (type === 'POST') {
o.setRequestHeader('Content-type',
'application/x-www-form-urlencode');
}
o.send(type === 'GET' ? null : formatData(data));
o.onreadystatechange = function(){
if (o.readyState === 4 && o.status === 200) {
success(JSON.parse(o.responseText));
}
if (o.status === 404) {
error();
}
complete();
}
function formatData(obj) {
var str = '';
for (var key in obj) {
str += key + '=' + obj[key] + '&'
}
return str.replace(/&$/, '');
}
}
return {
ajax: function(opt){
_doAjax(opt);
},
post: function(url, data, callback){
_doAjax({
type: 'POST',
url: url,
data: data,
success: callback
})
},
get: function(url, callback){
_doAjax({
type: 'GET',
success: callback
})
}
}
})();