完整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
};
})();

转载于:https://www.cnblogs.com/supreme-H/p/7486555.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值