1,request.js

function commonAjax(method, url, params, done) {
    // 统一转换为大写便于后续判断
    method = method.toUpperCase()
    // 对象形式的参数转换为 urlencoded 格式
    let pairs = []
    for (let key in params) {
        pairs.push(key + '=' + params[key])
    }
    let querystring = pairs.join('&')
    let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new
        ActiveXObject('Microsoft.XMLHTTP')
    xhr.addEventListener('readystatechange', function () {
        console.log(this.readyState)
        if (this.readyState !== 4)
            return
        try {
            done(JSON.parse(this.responseText))
        } catch (e) {
            done(this.responseText)
        }
    })
    if (method === 'GET') {
        url += '?' + querystring
    }
    xhr.open(method, url)
    
    let data = null
    if (method === 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        data = querystring
    }
    xhr.send(data)
}

2,使用request.js

commonAjax("post", url, params, function (data) {})

 

上一篇html为例:

<script src="../js/request.js"></script>
    function getRunData() {
      // 处理滚动条引起的宽度 默认无滚动条
      document.getElementsByClassName("table-content-fixed")[0].style = "";
      // 获取查询参数
      let params = {
        brand: document.getElementsByName("brand")[0].value,
        script: document.getElementsByName("script")[0].value,
        show: document.getElementsByName("orderShow")[0].checked,
        text: document.getElementsByName("text")[0].value,
        currentPage: currentPage,
        pageCount: 10,
      };
      let url = "";
      commonAjax("post", url, params, function (data) {
        if (data.code != 1) {
          console.log(data.msg);
        } else {
            let runDataList = data.result;
          // 处理滚动条引起的宽度 长度大于9出现滚动条
          if (runDataList.length > 9) {
            document.getElementsByClassName("table-content-fixed")[0].style =
              "width:calc(100% - 8px)";
          }
          // 清空执行结果
          let tbody = document.getElementsByTagName("tbody")[0];
          tbody.innerHTML = "";
          // 挂载执行结果
          runDataList.forEach((item, index) => {
            let tr = document.createElement("tr");
            for (let key in item) {
              let td = document.createElement("td");
              td.width = "125px";
              td.innerHTML = item[key];
              tr.appendChild(td);
            }
            tbody.append(tr);
          });
        }
      });
    }

 

 
posted on 2023-02-13 11:45  Zoie_ting  阅读(26)  评论(0编辑  收藏  举报