封装ajax方法
function ajaxRequest(type, url, data, callback, loading, cache) {
var ajaxConfig = {
url: '',
data: {},
callback: null,
loading: true,
cache: true,
async: true
};
// 判断每一个参数url的类型
// 如果是对象则是请求参数对象
// 如果是字符串则是请求URL,参数和回调要继续检测后面的参数
if (typeof url === 'string') {
ajaxConfig.url = url;
ajaxConfig.data = data;
ajaxConfig.callback = callback;
ajaxConfig.loading = typeof(loading) === 'undefined' ? true : loading;
ajaxConfig.cache = cache;
} else {
ajaxConfig = $.extend({}, ajaxConfig, url);
}
$.ajax({
type: type,
url: ajaxConfig.url,
data: ajaxConfig.data,
beforeSend: function() {
if (ajaxConfig.loading) { $.showLoading(); }
},
dataType: 'json',
cache: ajaxConfig.cache,
async: ajaxConfig.async,
success: function(re) {
if (ajaxConfig.loading) { $.hideLoading() };
if (re.result == 1) {
if (re.msg != '') {
$.toast(re.msg, function() {
if (re.redirect) {
window.location.href = re.redirect;
} else {
ajaxConfig.callback(re.data);
}
});
} else {
ajaxConfig.callback(re.data);
}
} else {
$.toast(re.msg, 'forbidden');
}
},
error: function(re) {
ajaxConfig.loading && $.hideLoading();
$.toast("Error", "forbidden");
console.error(re.responseText);
}
})
}
调用
function ajaxGet(url, data, callback, loading) {
ajaxRequest('get', url, data, callback, loading, true);
}
function ajaxPost(url, data, callback, loading) {
ajaxRequest('post', url, data, callback, loading, false);
}
试试 站长V587 /* 封装ajax函数
* @param {string}opt.type http连接的方式,包括POST和GET两种方式
* @param {string}opt.url 发送请求的url
* @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的
* @param {object}opt.data 发送的参数,格式为对象类型
* @param {function}opt.success ajax发送并接收成功调用的回调函数
*/
function ajax(opt) {
opt = opt || {};
opt.method = opt.method.toUpperCase() || 'POST';
opt.url = opt.url || '';
opt.async = opt.async || true;
opt.data = opt.data || null;
opt.success = opt.success || function () {};
opt.error = opt.error || function(){};
var xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
var params = [];
for (var key in opt.data){
params.push(key + '=' + opt.data);
}
var postData = params.join('&');
if (opt.method.toUpperCase() === 'POST') {
xmlHttp.open(opt.method, opt.url, opt.async);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send(postData);
}
else if (opt.method.toUpperCase() === 'GET') {
xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
xmlHttp.send(null);
}
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState === 4){
if (xmlHttp.status == 200) {
opt.success(xmlHttp.responseText);
}else{
opt.error();
}
}
};
}
我这个才是棒棒的ajax 封装,不依赖jQ:lol:lol
页:
[1]