現在的項目中都在用VUE 以及react 等MVC, MVVM 框架。 丟棄了原始的JQ 。不可能為了個$.ajax();而把JQ引進來吧。
在vue1的開發中 提供了 vueResouce, vue2 出來后明確提出了不在更新vueResouce 而提供axios 的方法。
在react 的開發中提供fetch 封裝的方法。等等。但在工作與后臺的交互中基本都是form表單的形式。于是自己封裝了個
POST,GET,DELETE 的請求方式。當然根據不同的公司,不同的方式。都可以自己擴展。目前這個只是針對自己所在公司而已。
function api(url,opt,methods) {      return new Promise(function(resove,reject){        methods = methods || 'POST';        var xmlHttp = null;        if (XMLHttpRequest) {          xmlHttp = new XMLHttpRequest();        } else {          xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');        };        var params = [];        for (var key in opt){          if(!!opt[key] || opt[key] === 0){            params.push(key + '=' + opt[key]);          }        };        var postData = params.join('&');        if (methods.toUpperCase() === 'POST') {          xmlHttp.open('POST', url, true);          xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');          xmlHttp.send(postData);        }else if (methods.toUpperCase() === 'GET') {          xmlHttp.open('GET', url + '?' + postData, true);          xmlHttp.send(null);        }else if(methods.toUpperCase() === 'DELETE'){          xmlHttp.open('DELETE', url + '?' + postData, true);          xmlHttp.send(null);        }        xmlHttp.onreadystatechange = function () {          if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {            resove(JSON.parse(xmlHttp.responseText));          }        };      });    }    export default api;以上這篇原生js 封裝get ,post, delete 請求的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答