简单封装1
function ajax(method,url,data,success) {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (method == 'get' && data) {
url+='?'+data;
}
xhr.open(method,url,true);
if (method == 'get') {
xhr.send();
}else {
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send(data)
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
success && success(xhr.responseText);
}else{
alert('出错了: '+xhr.status )
}
};
}
}
简单封装2
function ajax(opts) {
var xhr = null;
var options = {
method : 'GET',
url : '',
data : '',
async : true,
timeout : function(){},
success : function(){},
error : function(){}
}
for(var key in opts){
options[key] = opts[key]
}
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (options.method.toUpperCase() == 'GET'&& options.data) {
var empty = '';
for(var key in options.data ){
empty += encodeURI(key)+'='+encodeURI(options.data[key])+'&';
}
options.url+='?'+empty+new Date().getTime();
};
xhr.open(options.method,options.url,options.async);
if (options.method.toUpperCase() == 'GET') {
xhr.send();
}else{
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data='';
for(var key in options.data){
data += key +'='+options.data[key]+'&';
}
data.slice(0,-1)
xhr.send(data);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
options.success && options.success(xhr.responseText);
}else {
alert('出错了:' + xhr.status)
}
};
}
}
简单封装3 转载别人的
原文地址
function ajax(opts){
var defaults = {
method: 'GET',
url: '',
data: '',
async: true,
cache: true,
contentType: 'application/x-www-form-urlencoded',
success: function (){},
error: function (){}
};
for(var key in opts){
defaults[key] = opts[key];
}
if(typeof defaults.data === 'object'){
var str = '';
for(var key in defaults.data){
str += key + '=' + encodeURI(defaults.data[key]) + '&';
}
defaults.data = str.substring(0, str.length - 1);
}
defaults.method = defaults.method.toUpperCase();
defaults.cache = defaults.cache ? '' : '&' + new Date().getTime() ;
if(defaults.method === 'GET' && (defaults.data || defaults.cache)) {
defaults.url += '?' + defaults.data + defaults.cache;
}
var oXhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
oXhr.open(defaults.method, defaults.url, defaults.async);
if(defaults.method === 'GET')
oXhr.send(null);
else{
oXhr.setRequestHeader("Content-type", defaults.contentType);
oXhr.send(defaults.data);
}
oXhr.onreadystatechange = function (){
if(oXhr.readyState === 4){
if(oXhr.status === 200)
defaults.success.call(oXhr, oXhr.responseText);
else{
defaults.error();
}
}
};
}