完整Ajax公共函数的封装

/********************ajax公共函数************************/
(function () {

// 将json对象转换成查询字符串
var buildQueryString = function (parameter) {
var queryString = null;
if (parameter && typeof(parameter) === 'object') {
for (var key in parameter) {
if (queryString) {
queryString = queryString + key + '=' + parameter[key];
}
else {
queryString = key + '=' + parameter[key];
}
}
}
return queryString;
};

var getMethod = function (options) {
// 检查参数是否有效
if (options == null || typeof(options) !== 'object') {
throw '参数必须为json对象.';
}

// 检查url是否有效
if (options.url == null || options.url.length == 0) {
throw 'url不能为空.';
}

// 检查请求参数是否有效
if (options.param && typeof(options.param) !== 'object') {
throw '请求参数必须为json对象.';
}

// 检查回调函数是否有效
if (options.start && typeof(options.start) !== 'function'
|| options.complete && typeof(options.complete) !== 'function'
|| options.success && typeof(options.success) !== 'function') {
throw '回调必须为函数类型.';
}

// 构建查询参数
var queryString = null;

if (options.param) {
queryString = buildQueryString(options.param);
}

// 重新构建请求的url
var url = options.url;
if (null != queryString) {
url = url + '?' + queryString;
}

// 异步请求
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
if (options.start) {
xhr.onloadstart = options.start;
}
if (options.complete) {
xhr.onloadend = options.complete;
}
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
if (options.success) {
// 根据请求方的需求,返回特定格式的数据
if (options.returnType && options.returnType.toLowerCase() === 'json') {
// json
options.success(JSON.parse(this.responseText));
}
else {
// 字符串
options.success(this.responseText);
}

}
}
};
xhr.send(null);

};
var postMethod = function (options) {
var formData = new FormData();
// 封装请求参数
if (options.param && typeof(options.param) === 'object') {
for (var key in options.param) {
formData.append(key, options.param[key]);
}
}

var xhr = new XMLHttpRequest();
xhr.open('POST', options.url, true);
if (options.start) {
xhr.onloadstart = options.start;
}
if (options.complete) {
xhr.onloadend = options.complete;
}
xhr.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
if (options.success) {
// 根据请求方的需求,返回特定格式的数据
if (options.returnType && options.returnType.toLowerCase() === 'json') {
// json
options.success(JSON.parse(this.responseText));
}
else {
// 字符串
options.success(this.responseText);
}
}
}
}
xhr.send(formData);
};

// 封装ajax的get与post请求
window.ajax = {
get: getMethod,
post: postMethod
};
})();

posted @ 2017-09-06 19:36  平安喜乐  阅读(1152)  评论(0编辑  收藏  举报