zoukankan      html  css  js  c++  java
  • Javascript 封装的ajax方法

    //ajax的封装
    var Ajax = {
        method: 'post',
        asynchronous: true,
        proxy: null,
        contentType: "application/x-www-form-urlencoded",
    
        create: function () {
            var me = this, proxy;
            var xmlhttpObj = ['MSXML2.XMLHTTP.3.0',
                           'MSXML2.XMLHTTP',
                           'Microsoft.XMLHTTP'];
            if (window.XMLHttpRequest)// firefox 
            {
                proxy = new XMLHttpRequest();
            }
            else if (typeof ActiveXObject != "undefined")// IE 
            {
                for (var i = 0, len = xmlhttpObj.length; i < len; i++) {
                    if (!proxy)
                        proxy = new ActiveXObject(xmlhttpObj[i]);
                    else
                        break;
                }
            }
            return proxy;
        },
        stateChange: function (proxy, callback) {
            var me = this;
            var readyState = proxy.readyState;
            if (readyState == 4 && proxy.status == 200)
                (callback || function () { }).call(me, proxy.responseText, proxy);
        },
        analyzeParam: function (params) {
            var arrp = [];
            for (var p in (params || {})) {
                arrp.push("&" + p + "=" + params[p]);
            }
            return arrp.join().replace(/\,/g, "");
        },
        request: function (cfg) {
            var me = this;
            var proxy = me.create();
            if (proxy) {
                proxy.onreadystatechange = function () {
                    me.stateChange.call(me, proxy, cfg.callback);
                };
            }
            var param = me.analyzeParam(cfg.params);
            try {
                proxy.open(me.method, cfg.url, me.asynchronous);
                proxy.setRequestHeader("Content-type", me.contentType);
                proxy.send(me.analyzeParam.call(me, cfg.params));
            }
            catch (ex) {
                alert(ex.message)
            }
        }
    };
    
    
    //调用方法
    Ajax.request({
          url:"text.aspx",
          params:{name:'aa',age:20},
          callback:function(response){alert(response)}
    });
    
  • 相关阅读:
    发现可以用undef
    再改WUIBUTTON
    使用WUI点滴(一)
    关于IE里超链接失效的解决方案
    WUIButton的BUG
    GDI+ 你使用了吗?
    初次使用WUI
    判断键是否按下
    电梯坏了怎么办?
    在sdk中如何加入web浏览器的两种方法(转贴)
  • 原文地址:https://www.cnblogs.com/SunsetAndTea/p/1989966.html
Copyright © 2011-2022 走看看