• ajax自己封装


    function paramsSeralize(obj){
      if(!obj || typeof !== 'object') return obj;
      let res = '';
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          res += `&${key}=${obj[key]}`
        }
      }
      result = result.substring(1);
      return result;
    }
    function ajax (options) {
      let params = Object.assign({
        method: 'GET',
        url: '',
        data: null,
        params: null
      }, options)
      let isGet = /^(GET|OPTIONS|HEAD|DELETE)$/i.test(options.method)
    
      options.params ? options.params = paramsSeralize(options.params) : null;
    
      options.data ? options.data = paramsSeralize(options.data) : null;
    
      if(isGet && options.params){
        options.url += `${options.url.indexOf('?')>=0 ? '&' : '?'}${options.params}`
      }
    
      let xhr = new XMLHttpRequest;
      xhr.open(options.method, options.url)
    
      !isGet ? xhr.setRequestHeader('Content-type','x-www-form-urlencoded') : null;
    
      xhr.onreadystatechange = function () {
        let { readyState, status, responseText } = xhr;
        if (/^2d{2}/.test(status) && readyState === 4) {
          responseText = JSON.stringify(responseText)
          options.success && options.success()
        }
      }
      xhr.send(isGet ? null : options.data);
    }

    使用

    ajax({
      method: 'GET',
      url: '/user/list',
      data: {
        lx: 1,
        number: 2
      },
      params: {
        type: 1
      },
      success (res) {
    
      }
    })
  • 相关阅读:
    js选项卡
    js 逻辑运算符
    git 标签管理
    git多人协作
    git 分支强制删除
    git bug修复
    DOS命令编译JAVA程序
    JDK的安装与配置
    我在linux的第一个C程序
    看我如何在控制台一行显示几万字符。
  • 原文地址:https://www.cnblogs.com/qqfontofweb/p/13336706.html
Copyright © 2020-2023  润新知