Ajax第二篇:Ajax简单封装

概述

问题:发送一次请求代码过多,发送多次请求代码冗余且重复。

解决方案:将请求代码封装到函数中,发请求时调用函数即可。

封装

封装代码如下:

myAjax.js

(function (window) {
  /**
   * 
   * @param {*} option  配置对象
   * option.type    请求方式          string
   * option.url     请求的地址        string
   * option.data    请求的参数        object
   * option.success 成功回调函数      function   参数1:响应的数据;参数2:xhr对象
   * option.error   失败回调函数      function   参数1:状态码或错误消息;参数2:xhr对象或异常事件对象
   */
  function ajax(option) {
    /*默认配置对象 */
    var defaults = {
      type: 'get'
    };
    /*覆盖默认配置对象 */
    Object.assign(defaults, option)
    /* ajax */
    var xhr = new XMLHttpRequest();
    /*检测是否有请求参数 */
    if (defaults.data) {
      var paramsArr = []
      for (var key in defaults.data) {
        paramsArr.push(key+'=' + defaults.data[key])
      }
      var params = paramsArr.join('&')
      // get
      if (defaults.type.toLowerCase()  == 'get') {
        xhr.open('get',defaults.url+'?' + params)
        xhr.send()
      }
      // post
      else if (defaults.type.toLowerCase() == 'post') {
        xhr.open('post',defaults.url)
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(params)
      }
    }
    // 没有参数
    else {
      xhr.open(defaults.type.toLowerCase(), defaults.url)
      // 检测是否是post请求
      if (defaults.type.toLowerCase == 'post') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      }
      xhr.send()
    }
    // 监听响应
    xhr.onload = function () {
      if (xhr.status == 200) {
        defaults.success && defaults.success(xhr.responseText,xhr);
      } else {
        defaults.error && defaults.error(xhr.status,xhr)
      }
    }
    // 网络中断
    xhr.onerror = function (ev) {
      defaults.error && defaults.error('网络异常',ev)
    }
    

  }
  window.ajax = ajax;
})(window)

使用

后端程序

const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')

const app = express();
app.use(express.static(path.join(__dirname,'/public')))
app.use(bodyParser.urlencoded({ extend: false }))
 
app.get('/getAjax', (req, res) => {
  res.send(req.query)
})
app.post('/postAjax', (req, res) => {
  console.log(req.body)
  res.send(req.body)
})


app.listen(80, "localhost")

前端程序

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button id="btn1">get请求</button>
  <button id="btn2">post请求</button>
  <script src="./myajax.js"></script>
  <script>
    // get 
    btn1.onclick = function() {
      ajax({
        url: 'http://localhost/getAjax',
        success:function(data) {
          console.log(data)
        },
        data: {
          name: 'admin',
          age: 10
        },
        error: function(msg) {
          console.log(msg)
        }
      })
    }
    // post 
    btn2.onclick = function() {
      ajax({
        type:'post',
        url: 'http://localhost/postAjax',
        success:function(data) {
          console.log(data)
        },
        data: {
          name: 'admin',
          age: 10
        },
        error: function(msg) {
          console.log(msg)
        }
      })
    }
  </script>
</body>
</html>
posted @ 2020-05-11 23:41  雷哒哒  阅读(210)  评论(0编辑  收藏  举报