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:元素是通过指定的参数分隔符进行分隔的。

     
     
     
  • 相关阅读:
    Java中的transient关键字
    【笔记】html的改变(上)
    《开发板 — 实现看门狗》
    《头文件导致Symbol xxx multiply defined重复定义问题分析和解决》
    《APP读取按键值》
    《补充 — Linux内核device结构体分析(转)》
    《设备树LED模板驱动程序》
    《C库 — 字符串和整型数相互转换函数atoi和itoa》
    《Ubuntu — rsync命令》
    《Ubuntu — 2>/dev/null和>/dev/null 2>&1和2>&1>/dev/null的区别》
  • 原文地址:https://www.cnblogs.com/hynb/p/5863409.html
Copyright © 2011-2022 走看看