zoukankan      html  css  js  c++  java
  • 原生 js 封装get ,post, delete 请求

    现在的项目中都在用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;
  • 相关阅读:
    PAT:1075. PAT Judge (25) AC
    PAT:1010. 一元多项式求导 (25) AC
    PAT:1076. Forwards on Weibo (30) AC
    PAT:1086. Tree Traversals Again (25) AC
    PAT:1020. Tree Traversals (25) AC
    PAT:1051. Pop Sequence (25) AC
    PAT:1063. Set Similarity (25) AC
    PAT:1017. A除以B (20) AC
    C语言指针
    iOS block
  • 原文地址:https://www.cnblogs.com/createGod/p/7339850.html
Copyright © 2011-2022 走看看