原生js封裝ajax請求

一個完整的ajax請求封裝,適用場景:

  1. get 請求
  2. post請求
  3. 表單提交方式
  4. 表單上傳文件
function ajax(options) {
    var method = options.method || 'get'; //請求方法,默認get
    var url = options.url || ''; //請求url
    var succFn = options.success || function(){console.log('請求成功!')}; //請求成功回調
    var data = options.data || null; // 請求數據
    var isAsync = options.async === undefined ? true : options.async; //是否是異步請求,默認true
    var isFormData = options.isFormData || false; //是否採用表單提交數據的方式,默認false
	
	// 創建異步象
    var ajax = null;
    if(window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    }
    else {
        ajax = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    // get請求參數處理
    if (data && method.toLowerCase() === 'get') {
        url += '?';
        for(var key in data) {
            url += key + "=" + encodeURIComponent(data[key]) + "&";
        }
        url = url.slice(0, url.length - 1);
    }

    ajax.open(method, url, isAsync);
	
	// post請求處理, 非表單數據提交方式
    if(method.toLowerCase() == 'post' && !isFormData) {
        var contentType = "application/x-www-form-urlencoded";
        ajax.setRequestHeader("Content-type", options.contentType || contentType);
        
        if(data) {
            var dataJSON = '';
            for(var key1 in data) {
                dataJSON += key1 + "=" + encodeURIComponent(data[key1]) + "&"; 
                // encodeURIComponent 當get請求參數中有特殊字符時必須轉碼,否則會丟失特殊符號
            }
            dataJSON = dataJSON.slice(0, dataJSON.length - 1);
            ajax.send(dataJSON);
        } else {
            ajax.send();
        }

    }
	
	// post請求 表單數據提交方式
    if(isFormData) { 
        ajax.send(data);
    }

    if(method.toLowerCase() === 'get') {
        ajax.send();
    }

    ajax.onreadystatechange = function () {
        if (ajax.readyState==4 && ajax.status==200) {
            succFn(ajax);
        }
    }
}

使用方式:

ajax({
   method: 'get',
   url: 'http://127.0.0.1/ajax/url',
   data: {
   		id: id,
   		name: name
   },
   success: function(res) {
   		console.log(res);
   }
});
ajax({ 
  method: 'post',
   url: 'http://127.0.0.1/post/data/url',
   data: {
       name: name,
       id: id,
       type: type
   },
   success: function(res) {
   		console.log(res);
   }
})

表單方式提交異步請求:

var file = document.getElementById('file');
file.addEventListener('change', function() {  
   var files = this.files;

    var formData = new FormData();
    formData.append("files[]", files[0]); // []表示files字段的數據格式爲數組
    formData.append("parentId", '父級id');
    ajax({
       method: "post",
       url: 'http://127.0.0.1/upload/file/',
       contentType: "multipart/form-data",
       isFormData: true, // 使用表單數據提交方式
       data: formData,
       success: function(res) {
			console.log(res);
       }
   })
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章