AJAX请求函数封装(POST方式)

        // 请求函数封装
        var S_POST = function (url, opt, callback) {

            var that = this;
            var form = new FormData();
            var xhr = new XMLHttpRequest();

            // 请求入参处理
            for (var key in opt) { form.append(key, opt[key]); };
            // form.append('token', '');
            // form.append('requestId', '');
            // form.append('requestMsg', '');

            xhr.open('post', url, true);
            xhr.onload = function (e) {
                if (this.status == 200) {
                    var json;
                    try { json = JSON.parse(xhr.responseText); } catch (e) { json = {} };
                    callback && callback(json);
                } else {
                    callback && callback({ code: 4, msg: '返回错误' });
                }
            };

            xhr.timeout = 60000; // 超时时间,单位是毫秒
            xhr.ontimeout = function (e) { callback && callback({ code: 0, msg: '请求超时' }); };
            xhr.onerror = function (e) { callback && callback({ code: 0, msg: '请求错误' }); };

            xhr.send(form);
        };


        // 请求方法调用
        S_POST(url, option, function (json) {
           if(json.code == 200){
               console.log(json)
               // doSomething;
           }else{
               console.log(json.msg);
           }
        });
原文地址:https://www.cnblogs.com/lemen/p/13157459.html