插件_封装_ajax

1 ajax

1 Ajax 封装调用
ajax({
    url: './hh.php',
    type: 'post',
    data: {
      type: 'login',
      user: user.value,
      pass: pass.value
    },      // data: 'wd='+ ipt.value,  字符串拼接的方式
    dataType: 'json',
    success: function (data) {
      var json = JSON.parse(data);
      alert(json.msg);
    },
    error: function (status) {
      alert('提交失败');
    }
  });


2 Ajax 请求封装
function isObject(obj){
  if (Object.prototype.toString.call(obj) === '[object Object]'){
      return true;
  }
  return false;
}

function ajax(options){
  var xhr = new XMLHttpRequest();
  var data = '';
  if (typeof options.data === 'string') {
      data = options.data;
  }
  if ( isObject(options.data) ){
      for (var key in options.data){
          data += key+'='+options.data[key]+'&';
      }
      data = data.substring(0,data.length-1);
  }

  if (options.type.toLowerCase() === 'get') {
      xhr.open(options.type,options.url+'?'+data+'&_='+Date.now());
      xhr.send(null);
  }else if (options.type.toLowerCase() === 'post'){
      xhr.open(options.type,options.url);
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
      xhr.send(data);
  } else {
      alert('目前只支持get和post请求方式');
      return false;
  }
  xhr.onreadystatechange = function (){
      if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
              if (options.dataType === 'xml') {
                  options.success(xhr.responseXML);
              } else {
                  options.success(xhr.responseText);
              }
          } else {
              options.error(xhr.status);
          }
      }
  }
}

2 jsonp

1 jsonp封装调用
jsonp({
  url: 'http://suggestion.baidu.com/su',
  data: 'wd=' + search.value,
  jsonp: 'cb',  // 根据接口的回调函数名来输入
  jsonpCallback: 'mycb',  // 可以自定义, 全局函数的名字, 随便写啥都行
  success: function (json) {
    list.innerHTML = '';
    json.s.forEach(function (item) {
      list.innerHTML += '<li>' + item + '</li>';
    });
  }
})


2 jsonp封装
function isObject(obj){
  if (Object.prototype.toString.call(obj) === '[object Object]'){
      return true;
  }
  return false;
}

function jsonp(options) {
  // 把options.success变成全局函数
  window[options.jsonpCallback] = options.success;

  // 格式化参数
  var data = '';
  if (typeof options.data === 'string') {
    data = options.data;
  }
  if (isObject(options.data)) {
    for (var key in options.data) {
      data += key + '=' + options.data[key] + '&';
    }
    data = data.substring(0, data.length - 1);
  }

  // 创建 script 标签
  var oScript = document.createElement('script');
  // 把数据地址、参数、回调函数拼接赋值给src
  oScript.src = options.url + '?' + data + '&' + options.jsonp + '=' + options.jsonpCallback;
  // 添加到body中
  document.body.appendChild(oScript);
  // 数据加载完成后删除script标签
  oScript.onload = function () {
    document.body.removeChild(oScript);
  }
}

3 小功能

1 获取元素到最外层定位父级的距离, 也就是到body的距离, 放大镜很方便
----------------------------------------------------------------------------------------
function offset(dom,bool){
    var t = 0, l = 0
    var bdl = dom.clientLeft // 保存当前元素的左边框
    var bdt = dom.clientTop// 保存当前元素的上边框
    while(dom){
      l += dom.offsetLeft + dom.clientLeft
      t += dom.offsetTop + dom.clientTop
      // 每次循环完让当前dom元素等于他的定位父级
      dom = dom.offsetParent
    }
    if (bool) {// 包含自身边框
      return {left: l, top: t}
    } else {// 不包含自身边框
      return {left: l-bdl, top: t-bdt}
    }
  }
----------------------------------------------------------------------------------------

2 生成6位随机验证码  //数字、字母(大小写)
----------------------------------------------------------------------------------------
function randomCode() {
    var arr = [1, 1, 1, 1, 1, 1];
    for (var i in arr) {
        do {
            var ascii = randomInt(48, 122);
        } while ((ascii > 57 && ascii < 65) || (ascii > 90 && ascii < 97));
        arr[i] = String.fromCharCode(ascii);
    }
    return arr.join('');
}
----------------------------------------------------------------------------------------

3  生成区间随机整数
----------------------------------------------------------------------------------------
function randomInt(min, max) {
    return Math.round(Math.random() * (max - min)) + min;
}
----------------------------------------------------------------------------------------

4 生成随机的十六进制颜色值 #
----------------------------------------------------------------------------------------
function randomColor() {
    var str = '0123456789abcdef';
    var col = '#';
    for (var i = 0; i < 6; i++) {
        var index = randomInt(0, 15);
        col += str[index];
    }
    return col;
}
----------------------------------------------------------------------------------------

5 正则相关: 
----------------------------------------------------------------------------------------
1 正则  手机号: var reg = /^(\+861|1)[3-9][4-9]\d{8}$/;
2 正则  邮箱: var regEmail = /\w{6,24}@[0-9a-z]{1,10}(\.[a-z]{2,3}){1,2}/;
			 var regEmail = /\w{6,24}@\w+\.\w+/
----------------------------------------------------------------------------------------

6 获取当前日期格式化
----------------------------------------------------------------------------------------
function getTimes() {
    var date = new Date();

    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var dates = date.getDate();
    var day = date.getDay();
    var days = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    var h = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();

    month = month < 10 ? "0" + month : month;
    dates = dates < 10 ? "0" + dates : dates;
    h = h < 10 ? "0" + h : h;
    m = m < 10 ? "0" + m : m;
    s = s < 10 ? "0" + s : s;
    console.log(year + "年" + month + "月" + dates + "日 " + days[day] + " " + h + ':' + m + ':' + s);
}
getTimes();
----------------------------------------------------------------------------------------

7 倒计时案例: 
----------------------------------------------------------------------------------------
function countDown(time) {
    var nowTime = +new Date();  //当前时间戳
    var inputTime = +new Date(time);  //指定日期的时间戳
    var times = (inputTime - nowTime) / 1000;  //当前时间到指定时间的秒数

    var d = parseInt(times / 60 / 60 / 24);  //表示剩余的天数
    d = d < 10 ? "0" + d : d;
    var h = parseInt(times / 60 / 60 % 24);  //总秒数 / 60 (==总分钟数) / 60 (==总小时数) % 24 
    h = h < 10 ? "0" + h : h;
    var m = parseInt(times / 60 % 60);  //对应的分钟
    m = m < 10 ? "0" + m : m;
    var s = parseInt(times % 60);   //对应的秒
    s = s < 10 ? "0" + s : s;

    return d + "天" + h + "时" + m + "分" + s + "秒";
}
----------------------------------------------------------------------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值