zoukankan      html  css  js  c++  java
  • 封装一个ajax函数

    function ajax(data){
    //data={data:"",dataType:"xml/json",type:"get/post",url:"",asyn:"true/false",success:function(){},failure:function(){}}

    //data:{username:123,password:456}
    //data = 'username=123&password=456';
    //第一步:创建xhr对象
    var xhr = null;
    if(window.XMLHttpRequest){//标准的浏览器
    xhr = new XMLHttpRequest();
    }else{
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    //第二步:准备发送前的一些配置参数
    var type = data.type == 'get'?'get':'post';
    var url = '';
    if(data.url){
    url = data.url;
    if(type == 'get'){
    url += "?" + data.data + "&_t="+new Date().getTime();
    }
    }
    var flag = data.asyn == 'true'?'true':'false';
    xhr.open(type,url,flag);

    //第三步:执行发送的动作
    if(type == 'get'){
    xhr.send(null);
    }else if(type == 'post'){
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.send(data.data);
    }

    //第四步:指定回调函数
    xhr.onreadystatechange = function(){
    if(this.readyState == 4){
    if(this.status == 200){
    if(typeof data.success == 'function'){
    var d = data.dataType == 'xml'?xhr.responseXML:xhr.responseText;
    data.success(d);
    }
    }else{
    if(typeof data.failure == 'function'){
    data.failure();
    }
    }
    }
    }

    }

    不积小流,无以成江河!记住一万个小时定律!
  • 相关阅读:
    RabbitMQ学习笔记【1】
    【转】ES6学习笔记
    vue学习笔记【2】--模板语法
    vue学习笔记【1】
    npm使用
    Golang密码复杂度校验
    GORM的增删改查
    GORM:创建数据
    golang的time包:时间字符串和时间戳的相互转换
    输出10以内的所有正整数(while+if用法)
  • 原文地址:https://www.cnblogs.com/Ed-song/p/7709392.html
Copyright © 2011-2022 走看看