- (function (window) {
- //避免污染全局變量
- function ajax(options) {
- var init = {
- type: 'get',
- url: "",
- data: {},
- async: true,
- success: function (txt) {
- },
- error: function () {
- },
- cache: true,
- beforeSend: function () {
- },
- complete: function () {
- }
- };
- options = merge(init, options);
- options.data = hb(options.data);
- var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
- //用一個變量來保存是否是post提交方式 值爲布爾值
- var is_post = /^post$/i.test(options.type);
- //來判斷是否需要處理url get方式的data需要加到url中
- if (!is_post) {
- //沒有考慮到url可能已經有參數
- //優先級的問題 &的問題
- options.url += (options.url.indexOf('?') > -1 ? "&" : '?') + options.data;
- //處理緩存 是否加上時間戳
- options.url += options.cache ? "" : '&__time__=' + new Date().getTime();
- }
- xhr.open(options.type, options.url, options.async);
- //開始動畫
- options.beforeSend();
- //設置頭文件
- if (is_post) {
- xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- }
- xhr.send(options.data);
- xhr.onreadystatechange = function () {
- if (xhr.readyState == 4) {
- if (xhr.status == 200) {
- //提供xhr的使用權限 方便在使用時可以獲取xhr的其他屬性
- options.success(xhr.responseText, xhr);
- // complete();
- } else {
- options.error(xhr.status, xhr);
- }
- options.complete();
- }
- }
- }
- function merge(init, add) {
- for (var key in add) {
- if (key in init) {
- init[key] = add[key];
- }
- }
- return init;
- }
- function hb(obj) {
- var str = "";
- for(var key in obj){
- str+= key+'='+obj[key]+'&';
- }
- return str;
- }
- window.ajax=ajax;
- })(window);
簡單封裝ajax
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.