@拭目以待:首發(fā)于原生js實(shí)現(xiàn)ajax及get post方法
ajax原生實(shí)現(xiàn)溃斋,含 post與get方法。原碼如下:
/*
* ajax
* type === GET: data格式 name=baukh&age=29
* type === POST: data格式 { name: 'baukh', age:29 }
* 與 jquery 不同的是,[success, error, complete]返回的第二個(gè)參數(shù), 并不是返回錯(cuò)誤信息, 而是錯(cuò)誤碼
* */
var extend = require('./extend');
var utilities = require('./utilities');
function ajax(options) {
var defaults = {
url: null,// 請(qǐng)求地址
type: 'GET',// 請(qǐng)求類型
data: null,// 傳遞數(shù)據(jù)
headers: {},// 請(qǐng)求頭信息
async: true,// 是否異步執(zhí)行
beforeSend: utilities.noop,// 請(qǐng)求發(fā)送前執(zhí)行事件
complete: utilities.noop,// 請(qǐng)求發(fā)送后執(zhí)行事件
success: utilities.noop,// 請(qǐng)求成功后執(zhí)行事件
error: utilities.noop// 請(qǐng)求失敗后執(zhí)行事件
};
options = extend(defaults, options);
if (!options.url) {
utilities.error('jTool ajax: url不能為空');
return;
}
var xhr = new XMLHttpRequest();
var formData = '';
if (utilities.type(options.data) === 'object') {
utilities.each(options.data, function (key, value) {
if(formData !== '') {
formData += '&';
}
formData += key + '=' + value;
});
}else {
formData = options.data;
}
if(options.type === 'GET' && formData) {
options.url = options.url + (options.url.indexOf('?') === -1 ? '?' : '&') + formData;
formData = null;
}
xhr.open(options.type, options.url, options.async);
for (var key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
// xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// 執(zhí)行發(fā)送前事件
options.beforeSend(xhr);
// 監(jiān)聽(tīng)onload并執(zhí)行完成事件
xhr.onload = function() {
// jquery complete(XHR, TS)
options.complete(xhr, xhr.status);
};
// 監(jiān)聽(tīng)onreadystatechange并執(zhí)行成功失敗事件
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
// jquery success(XHR, TS)
options.success(xhr.response, xhr.status);
} else {
// jquery error(XHR, TS, statusText)
options.error(xhr, xhr.status, xhr.statusText);
}
};
xhr.send(formData);
}
function post(url, data, callback) {
ajax({ url: url, type: 'POST', data: data, success: callback });
}
function get(url, data, callback) {
ajax({ url: url, type: 'GET', data: data, success: callback });
}
module.exports = {
ajax: ajax,
post: post,
get: get
};
代碼中調(diào)用了 extend與 utilities類,如果想了解更多,請(qǐng)關(guān)注 jTool
@拭目以待
個(gè)人站點(diǎn):www.lovejavascript.com
表格管理插件:gridmanager.lovejavascript.com && github地址
QQ交流群 (452781895):How To Make Love
微信公眾賬號(hào):loveJavascript