使用過
jQuery
的同窗,應該對事件綁定方法ajax
有必定的瞭解。 在我的類庫jTool
中實現了這個方法,這裏就來細說下原生實現方式。前端
如下爲我的類庫jTool 中 Ajax 實現方式。 代碼中使用到一個基礎方法對象utilities ,該對象爲jTool 的基礎類。 若是想了解更多,能夠經過點擊進入查看原碼。jquery
/*
* ajax
* type === GET: data格式 name=baukh&age=29
* type === POST: data格式 { name: 'baukh', age:29 }
* 與 jquery 不一樣的是,[success, error, complete]返回的第二個參數, 並非返回錯誤信息, 而是錯誤碼
* */
var extend = require('./extend');
var utilities = require('./utilities');
function ajax(options) {
var defaults = {
url: null,// 請求地址
type: 'GET',// 請求類型
data: null,// 傳遞數據
headers: {},// 請求頭信息
async: true,// 是否異步執行
beforeSend: utilities.noop,// 請求發送前執行事件
complete: utilities.noop,// 請求發送後執行事件
success: utilities.noop,// 請求成功後執行事件
error: utilities.noop// 請求失敗後執行事件
};
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");
// 執行發送前事件
options.beforeSend(xhr);
// 監聽onload並執行完成事件
xhr.onload = function() {
// jquery complete(XHR, TS)
options.complete(xhr, xhr.status);
};
// 監聽onreadystatechange並執行成功失敗事件
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
};
複製代碼
隨筆一行 這是前端最好的時代, 這也是前端最壞的時代。 衆多前端框架滿天飛,隨着 jQuery 在前端行業的慢慢弱化,老是會有一種斯人遠去,何者慰籍的感受。互勉吧,各位。git
另推薦個表格組件gridManagergithub