封装Ajax中的get与post请求函数

789 阅读3分钟

       Ajax 是一种用于创建快速动态网页的技术,Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。与其说Ajax是一个技术,还不如说它是一系列技术的集合。

GET

get是Ajax中一种请求方式,请求的内容会存在请求头中,且参数的长度有限制,不安全的方面体现在是明文传输是方式。

下面是封装好的get请求函数:

/**ajax get请求
   * @param {string} url 请求路径
   * @param {object} query 请求要携带的参数
   */
  ajaxget (url,query,fn,isjson = true){
    //如果有query,再url后面拼接query
    if(query){
      url +='?';
      for(var key in query){
        url+=`${key}=${query[key]}&`;
      }
      //在拼接完成以后最后会多出一个&
      url = url.slice(0,-1);
    }
    //创建核心对象
    let xhr = new XMLHttpRequest();
    //打开连接
    xhr.open('get',url);
    //发送请求
    xhr.send();
    //监听状态改变
    xhr.onreadystatechange = function () {
      if(xhr.readyState === 4){
        if(xhr.status === 200){
          //表示请求成功
          //如果要转换json
          let res = isjson ? JSON.parse(xhr.responseText) : xhr.responseText;
          //回调函数的常规写法
          fn && fn(res); 
        }
      }
    }
  }

由于我的封装函数在utils中是用对象的封装方式,所以我调用时用:utils.ajaxget()

下面是html结构代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="utils.js"></script>
</head>
<body>
<button onclick="sendMsg()">发送请求</button>
<script>
  function sendMsg () {
    const id = prompt()
    utils.ajaxget('01.php', { id }, function (resp) {
      console.log(resp)
    },false)
  }
</script>
</body>
</html>

在以上代码中:

  • 01.php是作为路径传入的
  • {id}是结构赋值的方式
  • function(resp){ 是作为一个函数传入,当运行这里是,将回调到我的utils中,
  • consol.log(resp)
    }
  • isjson = true/false:表示是否转换格式,默认为true

下面的是php代码:

<?php

$id = $_GET['id'];

//根据$id去数据库里找当前的数据


$shop = array(
    "id" => $id,
    "title" =>"光碟",
    "price" =>1999
);
//把php的数据转成json格式的字符串返回给前端
echo json_encode($shop);
?>

POST

post请求方式对于参数无长度限制,并且请求的内容是放在请求体中的,相对于get方式来说更安全一些,因为你毕竟不能直观看到它嘛~也更常用一点。

下面是我封装的post请求函数:

/**ajax post请求
   * @param {string} url 请求路径
   * @param {object} query 请求要携带的参数
   * @param {function} fn 请求成功之后的回调函数
   * @param {boolean} [isjson] 请求数据是否为json 默认值为true
   */
   /** ajax post请求
   * @param {string} url 请求路径
   * @param {object} query  请求要携带的参数
   * @param {function} fn 请求成功之后的回调函数
   * @param {boolean} [isJson] 请求数据是否为json,默认值为true
   */
  ajaxpost (url, query, fn, isJson = true) {
    var str = ''
    if (query) {
      for (var key in query) {
        str += `${key}=${query[key]}&`
      }
      str = str.slice(0, -1)
    }
    var xhr = new XMLHttpRequest()
    xhr.open('post', url)
    // 把发送数据格式设置为urlencoded
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
    xhr.send(str)
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          var res = isJson ? JSON.parse(xhr.responseText) : xhr.responseText
          fn && fn(res)
        }
      }
    }
  }

调用的原理和get一样(utils.ajaxpost),不过在post函数中多了一个需要填写传输方式的地方 xhr.send(str),和xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded") 这两句代码。

下面是html结构代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="utils.js"></script>
</head>
<body>
  <button onclick="sendMsg()">发送请求</button>
  <script>
    function sendMsg () {
      const id = prompt()
      utils.ajaxpost('02.php', { id }, resp => {
        console.log(resp)
      })
    }
  </script>
</body>
</html>

在以上代码中:

  • 01.php是作为路径传入的
  • {id}是结构赋值的方式
  • function(resp){ 是作为一个函数传入,当运行这里是,将回调到我的utils中,
  • consol.log(resp)
    }
  • isjson = true/false:表示是否转换格式,默认为true

下面的是php代码:

<?php

$id = $_POST['id'];

//根据$id去数据库里找当前的数据


$shop = array(
    "id" => $id,
    "title" =>"光碟",
    "price" =>1999
);
//把php的数据转成json格式的字符串返回给前端
echo json_encode($shop);
?>