zoukankan      html  css  js  c++  java
  • ajax的请求,参数怎么管理?

     一般发送一条ajax 然后点击界面需要更改查询条件,第一种是做一个form表单比较合适的设计。更改了参数回收表单然后重新发送ajax;

    还有一种是把参数缓存到变量中,然后更改了条件修改变量再次重发ajax。

    我的是第二种思路实现方式如下:

     有不同见解的童鞋欢迎拍砖,接受任何方式的反驳 比如 微信红包走一波 。

    /**
     * =======================================================================
     ***--------------------------加载一个等待提示框--------------------------
     * =======================================================================
     * 配置项:{}
     *@target: "body",//需要展示的遮罩的对象
     *@cssName: "_showloading",//class名称,可以自定义class
     *@loadingImg: "/static/themes/vocs/ui-images/loading.gif",//遮罩图片的路径
     *@loadingText: "数据正在加载,请稍后...",//提示层的提示文字
     *@hideCall: null,//关闭回调函数
     *@timeout: 0//是否自动关闭
     * @param {Object} {target:'',cssName:'',loadingImg:'',loadingText:''}
     */
    function ShowLoading(opt) {
        // 默认配置项
        var _default = {
            'target': 'body', // 需要展示的遮罩的目标
            'cssName': '_showloading', // class名称,可以自定义class
            'loadingText': '数据正在加载,请稍后...', // 提示层的提示文字
            'hideCall': null, // 关闭回调函数
            'timeout': 0 // 是否自动关闭
        }
        $.extend(this, _default, opt)
        if (typeof this.target == 'string')
            this.target = $(this.target)
        if (typeof context != 'undefined')
            this.loadingImg = context + this.loadingImg
    }
    
    ShowLoading.prototype.show = function (msg, callBack) {
        var me = this
        var isBody = $(me.target).prop('nodeName') == 'BODY'
        // 获取目标的大小
        var getSize = function () {
            var scrollTop = isBody ? $(window).scrollTop() : $(me.target).scrollTop()
            var scrollLeft = isBody ? $(window).scrollLeft() : $(me.target).scrollLeft()
            // var w = isBody ? (scrollLeft+$(window).width()) : (scrollLeft+$(me.target).width())
            // var h = isBody ? (scrollTop + $(window).height()) : (scrollTop + $(me.target).height())
            var w = isBody ? ($(window).width()) : ($(me.target).width())
            var h = isBody ? ($(window).height()) : ($(me.target).height())
            return { w, height: h, scrollTop: scrollTop, scrollLeft: scrollLeft}
        }
        if (!this.$loading) {
            this.loadingId = '_load' + (new Date()).valueOf()
            if (!isBody)
                $(me.target).css('position', 'relative')
            this.$loading = $('<div>', {
                'id': this.loadingId,
                'class': this.cssName,
                // "style": "border:1px solid red",
                "html": "<div class='" + this.cssName + "-msg'>" + this.loadingText + "</div>"
            }).appendTo(this.target)
            var setPostion = function () {
                me.$loading.css({
                    //  getSize().width + "px",
                     getSize().width + 'px',
                    height: getSize().height + 'px',
                    top: getSize().scrollTop + 'px',
                    left: getSize().scrollLeft + 'px'
                })
                var sefWidth = me.$loading.children("." + me.cssName + "-msg").width(),
                    sefHeight = me.$loading.children("." + me.cssName + "-msg").height()
                me.$loading.children("." + me.cssName + "-msg").css({
                    'top': function () {
                        return parseInt((getSize().height - sefHeight) / 2) + 'px'
                    },
                    'left': function () {
                        return parseInt((getSize().width - sefWidth) / 2) + 'px'
                    }
                })
            }
            this.setPsIntv = setInterval(function () {
                setPostion()
            }, 50)
        }
        if (msg) {
            this.loadingText = msg
            this.$loading.children().text(msg)
        }
    
        // 是否有回调函数
        if (callBack != undefined && typeof callBack == 'function') {
            this.hideCall = callBack
        }
        // 是否是定时关闭
        if (this.timeout > 0) {
            setTimeout(function () {
                me.hide()
            }, this.timeout)
        }
        return this
    }
    ShowLoading.prototype.hide = function () {
        if (this.$loading) {
            this.$loading.remove()
            this.$loading = null
        }
        if (typeof this.hideCall == 'function') {
            this.hideCall()
        }
        if (this.setPsIntv)
            clearInterval(this.setPsIntv)
    }
    ShowLoading.prototype.update = function (msg) {
        if (this.$loading) {
            this.$loading.children().text(msg);
        }
    }
    View Code
    /**
     * AJAX构造函数
     * @param url 请求地址 String
     * @param param 请求参数 Object
     * @param callback 回调函数 Function
     */
    function AJAX_Method(url, param, callback) {
        this.url = url;
        this.param = param;
        this.callback = callback;
        this.method = "GET";
        this.isLoading = false;
    }
    
    /*扩展实例方法*/
    AJAX_Method.prototype = {
        /**
         *get请求
         */
        get: function () {
            var _this = this;
            if (_this.isLoading) {
                _this.showLoading();
            }
            $.get(_this.url, _this.param, function (response) {
                if (_this.isLoading) {
                    _this.hideLoading();
                }
                _this.callback(response);
            });
        },
        /**
         *post请求
         */
        post: function () {
            var _this = this;
            if (_this.isLoading) {
                _this.showLoading();
            }
            $.post(_this.url, _this.param, function (response) {
                if (_this.isLoading) {
                    _this.hideLoading();
                }
                _this.callback(response);
            });
        },
        /**
         * 重新请求
         * @param name 参数名称 | 对象
         * @param value 参数值
         */
        reload: function (name, value) {
            if (name) {
                this.setParam(name, value);
            }
            this.method.toLocaleLowerCase() == "get" ? this.get() : this.post();
        },
        /**
         * 获取请求参数
         * @returns {*}
         */
        getParam: function () {
            return this.param;
        },
        /**
         * 设置参数
         * @param name 参数名称 | 对象
         * @param value 参数值
         */
        setParam: function (name, value) {
            if (typeof name == "string") {
                this.param[name] = value;
            } else {
                $.extend(this.param, name)
            }
    
        },
        /**
         * 展示遮罩动画
         */
        showLoading: function (opt) {
            if (this.loading) {
                this.hideLoading();
            }
            this.loading = getTopWindow().AJAX_Loading(opt);
        },
        /**
         * 影藏遮罩动画
         */
        hideLoading: function () {
            if (this.loading) {
                this.loading.hide();
                this.loading = null;
            }
        }
    }
    
    /**
     *
     * @returns {Window | WorkerGlobalScope}
     */
    function getTopWindow() {
        var _top = self;
        while (_top != _top.parent) {
            if (typeof _top.parent.AJAX_Method != "undefined") {
                _top = _top.parent;
                continue;
            }
            break;
        }
        return _top;
    }
    
    /**
     * 封装get请求
     */
    function AJAX_GET(url, param, callback) {
        var ajax = new AJAX_Method(url, {}, new Function());
        //处理参数无序
        for (var i = 1; i < arguments.length; i++) {
            var parameter = arguments[i];
            var typeName = typeof parameter;
            if ("boolean" == typeName) {
                ajax.isLoading = parameter;
            } else if ("object" == typeName) {
                ajax.param = parameter;
            } else if ("string" == typeName) {
                ajax.method = parameter;
            } else if ("function" == typeName) {
                ajax.callback = parameter;
            }
        }
        //发送请求
        ajax.get();
        return ajax;
    }
    
    /**
     * 封装post请求
     */
    function AJAX_POST(url, param, callback) {
        var ajax = new AJAX_Method(url, {}, new Function());
        //处理参数无序
        for (var i = 1; i < arguments.length; i++) {
            var parameter = arguments[i];
            var typeName = typeof parameter;
            if ("boolean" == typeName) {
                ajax.isLoading = parameter;
            } else if ("object" == typeName) {
                ajax.param = parameter;
            } else if ("string" == typeName) {
                ajax.method = parameter;
            } else if ("function" == typeName) {
                ajax.callback = parameter;
            }
        }
        ajax.method = "POST";
        //发送请求
        ajax.post();
        return ajax;
    }
    
    /**
     * 展示动画
     * @param opt
     * @returns {ShowLoading|ShowLoading}
     * @constructor
     */
    function AJAX_Loading(opt) {
        var loading = new ShowLoading(opt);
        loading.show();
        return loading;
    }
    
    //测试示例:
    
    
    //标准发送请求
    var getUserInfo = AJAX_GET("test.json", {name: "张三李四"}, function (data) {
        alert(1);
    }, true);
    // 参数无序调用
    /*var getUserInfo2 = AJAX_GET("test.json", function (data) {
        alert(1);
    })*/
    
    
    //设置单个参数
    getUserInfo.setParam("name", "李四张三");
    //设置多参数
    getUserInfo.setParam({"name":"李四张三","time": "2019/12/04"});
    
    console.log(getUserInfo.param);
    //刷新结果
    getUserInfo.reload({"time": "2019/12/12"});
    //或者
    getUserInfo.get();
    //把请求方式修改成post
    getUserInfo.post();
    AJAX_Method

    观察network 视图效果如下: 

     

     

     

     是不是能 愉快的玩耍了

    如果这篇文章对您有帮助,您可以打赏我

    技术交流QQ群:15129679

     
     
  • 相关阅读:
    mysql备份
    Linux 配置参考
    oracle补丁安装
    多智能体城市交通计算综合应用
    基于纳什均衡的多智能体强化学习交通信号控制
    多智能体强化学习在城市交通信号控制中的研究与应用- 笔记
    Sarsa与Q-learning
    Pandas笔记
    Python学习笔记
    Game Theory and Multi-agent Reinforcement Learning笔记 下
  • 原文地址:https://www.cnblogs.com/yeminglong/p/10625586.html
Copyright © 2011-2022 走看看