當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
原生JS封装ajax以及request
生活随笔
收集整理的這篇文章主要介紹了
原生JS封装ajax以及request
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、封裝原生的xhr為ajax類
xhr以及用法見之前的文章1、根據url確定請求的頭部以及別的信息。
var _headerConfig = {};if(url.indexOf('getcaptcha') !== -1) {_headerConfig = {Accept: 'image/png',responseType: 'arraybuffer',}} else if(url.indexOf('files/upload') !== -1) {_headerConfig = {'Content-Type': 'multipart/form-data',responseType: 'json',}} else {_headerConfig = {'Content-Type': 'application/json',Accept: 'application/json',responseType: 'json',}}2、根據參數信息中的信息,確定請求的方法以及請求的參數
if("method" in options) {options.method = options.method.toUpperCase();} else {options.method = "GET";}if(options.method !== "GET") {if(!(options.params instanceof FormData)) {options.params = JSON.stringify(options.params);}}3、打開xhr并且根據頭部頭部以及其他信息設置,發送
this.xhr.open(options.method, url, true);for(var _i in _headerConfig) {if(_i === 'responseType') {this.xhr.responseType = _headerConfig[_i];} else {this.xhr.setRequestHeader(_i, _headerConfig[_i]);}}if(token) {this.xhr.setRequestHeader("token", token);}this.xhr.send(options.params);4、實現鏈式編程:在每個函數的結尾return this;
5、實現完成后執行回調
這個問題結合鏈式編程一度的卡了很久。
ajax.prototype.complete = function(completeFunction) {this.xhr.onreadystatechange = function(e) {if(this.readyState === 4) {completeFunction(this);}}return this; }二、封裝實用性的request類
在項目中經常需要將request進行封裝,使用ajax類發起請求。拼接請求的地址函數。1、創建拼接方法。
var requstUrl = {baseURL: URL,API: {NEWS: '/news',LOGIN: '/',},// api為API中的參數,用于拼接url// method為API后的地址,用于拼接url最后面的東西。// params為get請求需要的參數createUrl: function(api, method, params) {var _requestUrl = this.baseURL this.API[api] method;if(params) {for(var i of params) {_requestUrl = (_requestUrl.indexOf("?") == -1 ? "?" : "&");_requestUrl = name "=" value;}}return _requestUrl;} }2、確定各個請求。
function handleRequest() {}// get請求帶參數。 handleRequest.prototype.getDataUseGet = function(api, method, params) {var _url;var ajax = new Ajax();var token = sessionStorage.getItem('token');if(params) {_url = requstUrl.createUrl(api, method, params);} else {_url = requstUrl.createUrl(api, method);}return ajax.request(_url, {method: 'GET',params: params}, token); }// get請求不帶token handleRequest.prototype.getDataUseGetWithoutToken = function(api, method, params) {var _url;var ajax = new Ajax();if(params) {_url = requstUrl.createUrl(api, method, params);} else {_url = requstUrl.createUrl(api, method);}return ajax.request(_url, {method: 'GET',params: params}); }// post請求帶token handleRequest.prototype.getDataUsePost = function(api, method, params) {var _url = requstUrl.createUrl(api, method);var token = sessionStorage.getItem('token');var ajax = new Ajax();console.log(createAjaxObj(_url, {method: 'POST',params: params}, token));return ajax.request(_url, {method: 'POST',params: params}, token); }// post請求不帶token handleRequest.prototype.getDataUsePostWithOutToken = function(api, method, params) {var _url = requstUrl.createUrl(api, method);var ajax = new Ajax();return ajax.request(_url, {method: 'POST',params: params}); }// put請求帶token handleRequest.prototype.getDataUsePut = function(api, method, params) {var _url = requstUrl.createUrl(api, method);var token = sessionStorage.getItem('token');var ajax = new Ajax();return ajax.request(_url, {method: 'PUT',params: params}, token); }// put請求不帶token handleRequest.prototype.getDataUsePutWithOutToken = function(api, method, params) {var _url = requstUrl.createUrl(api, method);var ajax = new Ajax();return ajax.request(_url, {method: 'PUT',params: params}); }// delete請求帶token handleRequest.prototype.deleteData = function(api, method, params) {var _url = requstUrl.createUrl(api, method);var token = sessionStorage.getItem('token');var ajax = new Ajax();return ajax.request(_url, {method: 'DELETE',params: params}, token); } 這個方法感覺可以再次進行封裝。三、使用
1、使用代碼
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title></title></head><body></body><script src="ip.js" type="text/javascript"></script><script src="xhr.js" type="text/javascript"></script><script src="request.js" type="text/javascript"></script><script type="text/javascript">var data = {"captcha": "string","password": "string","username": "string"};var test = new handleRequest();test.getDataUsePostWithOutToken('LOGIN', 'login',data).complete(function(result) {console.log(result)})</script></html>2、結果
成功發起請求。
完整代碼點擊查看
以上。
原文地址:https://segmentfault.com/a/1190000017006833
更多專業前端知識,請上 【猿2048】www.mk2048.com
總結
以上是生活随笔為你收集整理的原生JS封装ajax以及request的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [vue插件]基于vue2.x的电商图片
- 下一篇: JS实现2048