封装AJAX

 //封装ajax
 function ajax(obj){
        
    //创建XMLHttpRequest对象
    if(window.XMLHttpRequest){
        var xhr = new XMLHttpRequest();
    }else{
        var xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    
    obj.url = obj.url+'?rand='+Math.random();      //使用js随机字符串解决IE第二次它就默认获取缓存数据,导致数据不更新
    
    obj.data = (function(data){                         //名值对转换为字符串闭包的方式调用
        var arr = [];
        for(var i in data){
            arr.push(encodeURIComponent(i)+'='+encodeURIComponent(data[i]));
        }
        return arr.join('&');
    })(obj.data);
    if(obj.method === 'get')obj.url += obj.url.indexOf('?') == -1?'?'+obj.data:'&'+obj.data;
    
    if(obj.async === true){
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                callback();
            }
        };
    }

    
    xhr.open(obj.method,obj.url,obj.async);
    if(obj.method === 'post'){
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');        //模仿表单提交
        xhr.send(obj.data);
    }else{
        xhr.send(null);
    }
    if(obj.async === false){
        callback();
    }
    
    
    function callback(){
        if(xhr.status == 200){
            obj.success(xhr.responseText);                                        //函数回调
        }else{
            alert('获取数据失败!错误代号:'+xhr.status+',错误信息:'+xhr.statusText);
        }
    }
}


    //调用ajax
    $(document).click(function(){
        ajax({
        method : 'post',
        url : 'demo.php',
        data : {
            'name' : 'Lee',
            'age' : 100
        },
        success : function (text) {
            alert(text);
        },
        async : true
        });
    });

 

encodeURIComponent(URIstring)函数可把字符串作为 URI 组件进行编码。

PS:encodeURIComponent() 函数将转义(;/?:@&=+$,#)这些用于分隔 URI 组件的标点符号

 

indexOf()返回某个指定的字符串值在字符串中首次出现的位置。

PS:如果要检索的字符串值没有出现,则该方法返回 -1。

 

join() 方法用于把数组中的所有元素放入一个字符串。

PS:元素是通过指定的参数分隔符进行分隔的。

 
 
 
posted @ 2014-09-12 03:16  胡小生  阅读(296)  评论(0编辑  收藏  举报