zoukankan      html  css  js  c++  java
  • 封装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:元素是通过指定的参数分隔符进行分隔的。

     
     
     
  • 相关阅读:
    【转】CUDA5/CentOS6.4
    【转】centos 6.4 samba 安装配置
    【转】Install MATLAB 2013a on CentOS 6.4 x64 with mode silent
    【转】Getting xrdp to work on CentOS 6.4
    【VLFeat】使用matlab版本计算HOG
    Unofficial Windows Binaries for Python Extension Packages
    March 06th, 2018 Week 10th Tuesday
    March 05th, 2018 Week 10th Monday
    March 04th, 2018 Week 10th Sunday
    March 03rd, 2018 Week 9th Saturday
  • 原文地址:https://www.cnblogs.com/hynb/p/5863409.html
Copyright © 2011-2022 走看看