Ajax




    
    Ajax


    




Javascript

(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  (global.Ajax = factory());
})( this, (function () { 
    'use strict';
    /**
     * [extend]
     * @param  {[Object]} chd [children]
     * @param  {[Object]} far [parent]
     * @return {[Object]}     
     */
    function extend(chd,far){
        for(var x in far){
            far[x] && (chd[x]=far[x]);
        }
    }
    /**
     * [O_to_S change object to string]
     * @param {[Object]} obj
     * @return {String}
     */
    function O_to_S(obj,post){
        var result='',reg=/^\?/,reg2=/^\&/;
        for(var x in obj){
            if (!post) {
                if (!reg.test(result)) {
                    result+='?'+x+'='+obj[x];
                }else{
                    result+='&'+x+'='+obj[x];
                }
            }else{
                if (!reg2.test(result)) {
                    result+=x+'='+obj[x]+'&';
                }else{
                    result+=x+'='+obj[x];
                }
            }
        }
        return result;
    }
    function Ajax(ops){
        var def={
            url:'',
            type:'GET',
            data:null,
            dataType:'json',    
            async:true,         
            timeout:5000,           
            beforeSend:null,
            complete:null,
            success:null,
            error:null
        };
        extend(def,ops);
        if (def.url==='') {alert('Request address is empty!');return;}

        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
        xhr.timeout=def.timeout;//请求超时
        xhr.ontimeout=function(){
            alert('request timeout!');
        };
        xhr.onloadstart=def.beforeSend;//请求开始

        if (def.type.toUpperCase()==='GET') {
            var dataString=O_to_S(def.data);
            if ( dataString !== '') {
                def.url += dataString;
            }
        }

        xhr.onreadystatechange = function(){
            if (xhr.readyState === 4) {
                def.complete();//请求完成
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                    
                    var options_type=def.dataType.toLowerCase(),xhrdata;
                    if (options_type === 'xml') {
                        xhrdata = xhr.responseXML;
                    }else if(options_type === 'json'){
                        xhrdata = window.JSON && window.JSON.parse ? JSON.parse(xhr.responseText) : eval('(' + xhr.responseText + ')');
                    }else{
                        xhrdata = xhr.responseText;
                    }
                    def.success(xhrdata);//请求成功

                } else {
                    def.error && def.error();
                    //console.log(xhr.status, xhr.statusText);
                }

            }

        };
        xhr.open( def.type.toUpperCase() , def.url , def.async );
        if (def.type.toUpperCase()==='POST') {
            xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');//请求头很重要 xhr.open后添加
            xhr.send( O_to_S(def.data,true) );
        }else{
            xhr.send();
        }
        //console.log(O_to_S(def.data,true))
    }
    return Ajax;
}))

PHP


你可能感兴趣的:(Ajax)