程序员

Ajax笔记

2018-08-29  本文已影响6人  android小菜鸡一枚
什么事Ajax?

AJAX是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下

创建步骤
xmlhttp.onreadystatechange = function() {
  // 0: 请求未初始化
  // 1: 服务器连接已建立
  // 2. 请求已接收
  // 3. 请求处理中
  // 4. 请求已完成,且响应已就绪
  if(xmlhttp.readystate === 4) {
    // 处理返回的结果
    if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
        //接收到服务器返回的数据
        xml.responseText;
    } else {
    
    }
  }
}
var xhr;
if(window.XMLHttpRequest) {
  // code for IE7+,Firefox, Chrome, Opera, Safari
  xhr = new XMLHttpRequest();
} else {
  // code for IE6,IE5
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

在IE浏览器中,如果通过Ajax发送GET请求,那么IE浏览器认为同一个URL只有一个结果 ,给URL添加一个参数就可以了xhr.open("GET","get.php?t="+ (new Date().getTime()),true);

/**
 *
 * @param data
 * @returns {string}
 */
// 将对象转换为字符串
function obj2str(data) {
    data.t = new Date().getTime();
    var res = [];
    for (var key in data) {
        // 在URL中是不可以出现中文的,如果出现了中文需要转码,可以调用encodeURLComponent
        res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));
    }
    return res.join("&");
}

/**
 *
 * @param option
 */
function ajax(option) {
    var str = obj2str(option.data);
    var xmlhttp, timer;
    if(window.XMLHttpRequest) {
        // code for IE7+,Firefox, Chrome, Opera, Safari
        xmlhttp= new XMLHttpRequest();
    } else {
        // code for IE6,IE5
        xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (option.type.toLowerCase() === "get") {
        xmlhttp.open(option.type,option.url+"?"+str,true);
        xmlhttp.send();
    } else {
        xmlhttp.open(option.type,option.url,true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(str);
    }

    xmlhttp.onreadystatechange = function() {
        // 0: 请求未初始化
        // 1: 服务器连接已建立
        // 2. 请求已接收
        // 3. 请求处理中
        // 4. 请求已完成,且响应已就绪
        if(xmlhttp.readystate === 4) {
            clearInterval(timer);
            // 处理返回的结果
            if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
                option.success(xmlhttp);
            } else {
                option.error(xmlhttp);
            }
        }
    }

    // 判断外界是否传入了超时时间
    if(option.timeout){
        timer = setInterval(function() {
            xmlhttp.abort();
            clearInterval(timer);
        }, option.timeout);
    }
}

// 调用
ajax({
  url:"",
  data:"",
  type:"",
  timeout:3000,
  success:function(xhr) {},
  error:function(xhr){}
})
jQuery ajax
$.ajax({
  type:"GET",
  url:"",
  data:"userName=lnj&userPwd=123",
  success:function(msg){
    var obj = eval("("+msg+")");//处理非标准JSON字符串
    $.each(obj, function(key, value) {})
  },
  error:function(xhr){
    alert(xhr.status);
  }
})

在低版本的IE中, 不可以使用原生的JSON.parse方法,可以使用json2.js框架来兼容
事件委托
$("body").delegate(".info",click,function(){});

cookie

cookie: 会话跟踪技术 客户端
session: 会话跟踪技术 服务端

var date = new Date();
date.setDate(date.getDate() + 1);
document.cookie = "age=33;expires="+date.toGMTString()+";";
/**
 * 添加cookie
 * @param key
 * @param value
 * @param day 过期时间
 * @param path
 * @param domain
 */
function addCookie(key,value,day,path,domain) {
    // 1.处理默认保存的路径
    var index = window.location.pathname.lastIndexOf("/");
    var currentPath = window.location.pathname.slice(0,index);
    path = path || currentPath;
    // 2.处理默认保存的domain
    domain = domain || document.domain;
    // 3.处理默认保存的domain
    if (!day) {
        document.cookie = key+"="+value+";path="+path+";domain="+domain+";";
    } else {
        var date = new Date();
        date.setDate(date.getDate() + day);
        document.cookie = key+"="+value+";expires="+date.toGMTString()+";path="+path+";domain="+domain+";";
    }
}

/**
 * 获取cookie
 * @param key
 * @returns {string}
 */
function getCookie(key) {
    var res = document.cookie.split(":");
    for(var i=0;i<res.length;i++) {
        var temp = res[i].split("=");
        if (temp[0].trim() === key) {
            return temp[1];
        }
    }
}

/**
 * 删除cookie
 * @param key
 */
function delCookie(key,path) {
    addCookie(key,getCookie(key),-1,path);
}
;(function ($,window) {
    $.extend({
        /**
         * 添加cookie
         * @param key
         * @param value
         * @param day 过期时间
         * @param path
         * @param domain
         */
        addCookie: function(key,value,day,path,domain) {
            // 1.处理默认保存的路径
            var index = window.location.pathname.lastIndexOf("/");
            var currentPath = window.location.pathname.slice(0,index);
            path = path || currentPath;
            // 2.处理默认保存的domain
            domain = domain || document.domain;
            // 3.处理默认保存的domain
            if (!day) {
                document.cookie = key+"="+value+";path="+path+";domain="+domain+";";
            } else {
                var date = new Date();
                date.setDate(date.getDate() + day);
                document.cookie = key+"="+value+";expires="+date.toGMTString()+";path="+path+";domain="+domain+";";
            }
        },

        /**
         * 获取cookie
         * @param key
         * @returns {string}
         */
        getCookie: function(key) {
            var res = document.cookie.split(":");
            for(var i=0;i<res.length;i++) {
                var temp = res[i].split("=");
                if (temp[0].trim() === key) {
                    return temp[1];
                }
            }
        },

        /**
         * 删除cookie
         * @param key
         */
        delCookie: function(key,path) {
            addCookie(key,getCookie(key),-1,path);
        }
    });
})(jQuery,window);

李南江亲授-jQuery+Ajax从放弃到知根知底

上一篇 下一篇

猜你喜欢

热点阅读