码迷,mamicode.com
首页 > Web开发 > 详细

封装的ajax.js

时间:2017-10-31 12:38:47      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:window   hang   异步   直接   open   formdata   http   typeof   text   

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

 

用到原生JS,ajax请求,此脚本直接引用,无副作用。

封装的ajax.js

标签:window   hang   异步   直接   open   formdata   http   typeof   text   

原文地址:http://www.cnblogs.com/skyforever/p/7760414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!