jquery ajax、fetch、axios网络请求组件和FormData简单使用

几种常见的Content-Type类型

application/x-www-form-urlencoded  数据会转换为键值对并按照 key1=val1&key2=val2 的方式进行编码,key 和 val 都进行了 URL 转码。

multipart/form-data(带文件提交) 将表单的数据处理为一条消息,以标签为单元,用分隔符分开

application/json 数据处理为序列化后的 JSON 字符串

application/octet-stream 二进制文件流

text/xml 用于传输和存储数据

FormData使用

//新建FormData对象
// const formData = new FormData();

//绑定form表单的FormData对象
const formData = new FormData(document.getElementById(domId));

//添加数据
formData.append("k1", "v1");
formData.append("k1", "v2");
formData.append("k1", "v1");

//根据key获取数据
console.log(formData.get("k1"));
console.log(formData.getAll("k1"));

//更新数据
formData.set("k1", "1");
console.log(formData.getAll("k1"));

//根据key判断是否有某个key
console.log(formData.has("k1"));

//根据key删除数据
formData.delete("k1");
console.log(formData.has("k1"));

formData.set("k1", "v1");
//遍历
for (let [index, item] of formData.entries()) {
    console.log(index, item);
}

 jquery ajax post请求

<form id="form">
    <input type="text" name="name" value="aa" />
    <input type="file" name="file" />
</form>
<button type="button" onclick="jqAjaxFormSerialize('form')">jquery ajax form serialize</button>
<button type="button" onclick="jqAjaxFormData('form')">jquery ajax formdata</button>
<button type="button" onclick="jqAjaxJson()">jquery ajax json</button>
  <script>
    const url = "http://localhost:3000/php-demos/request.php";
    // -------------------jquery ajax---------------
    // jQuery中content-type默认值为application/x-www-form-urlencoded

    function jqAjaxFormSerialize(domId) {
      const serializeData = $("#" + domId).serialize();
      $.ajax({
        url: url,
        type: "post",
        data: serializeData,
        dataType: "json",
        beforeSend: function () {},
        success: function (res) {
          console.log(res);
        },
        error: function (jqXHR, textStatus, errorThrown) {
          console.log(textStatus, errorThrown);
        },
      });
    }

    function jqAjaxFormData(domId) {
      const formData = new FormData(document.getElementById(domId));
      $.ajax({
        type: "post",
        url: url,
        data: formData,
        dataType: "json",
        cache: false,
        processData: false,
        contentType: false,
        beforeSend: function () {},
      })
        .done(function (result, textStatus, jqXHR) {
          console.log(result, textStatus);
        })
        .fail(function (jqXHR, textStatus, errorThrown) {
          console.log(textStatus, errorThrown);
        })
        .always(function (data, textStatus, jqXHR) {
          // console.log(data, textStatus);
        });
    }

    function jqAjaxJson() {
      $.ajax({
        url: url,
        type: "post",
        cache: false,
        data: dataStr,
        dataType: "json",
        processData: false,
        contentType: "application/json",
        success: function (res) {
          console.log(res);
        },
        beforeSend: function () {},
        error: function () {},
      });
    }
  </script>

 request.php

<?php

$rawData = file_get_contents('php://input');
$json_data = json_decode($rawData, true);
echo json_encode(['data' => $_REQUEST, 'file' => $_FILES, 'raw_data' => $rawData, 'json' => $json_data]);

响应

//发送表单序列化数据的响应
{"data":{"name":"aa"},"file":[],"raw_data":"name=aa","json":null}

//发送FormData数据的响应
{"data":{"name":"aa"},"file":{"file":{"name":"notes.txt","type":"text\/plain","tmp_name":"C:\\Users\\phpB5C1.tmp","error":0,"size":1926}},"raw_data":"","json":null}  "success"

//发送json数据的响应
{"data":[],"file":[],"raw_data":"{\"a\":1,\"b\":2}","json":{"a":1,"b":2}}

fetch

<button type="button" onclick="fetchFormSerialize('form')">fetch form serialize</button>
<button type="button" onclick="fetchFormData('form')">fetch formdata</button>
<button type="button" onclick="fetchJson()">fetch json</button>
  <script>
    function fetchFormSerialize(domId) {
      const serializeData = $("#" + domId).serialize();
      fetch(url, {
        method: "post",
        body: serializeData,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      })
        .then((res) => {
          if (!res.ok) {
            throw new Error(res.statusText);
          }
          return res.json();
        })
        .then((res) => console.log(res))
        .catch((error) => console.log(error));
    }

    function fetchFormData(domId) {
      const formData = new FormData(document.getElementById(domId));
      fetch(url, {
        method: "post",
        body: formData,
      })
        .then((res) => {
          if (!res.ok) {
            throw new Error(res.statusText);
          }
          return res.json();
        })
        .then((res) => console.log(res))
        .catch((error) => console.log(error));
    }

    function fetchJson() {
      const dataStr = JSON.stringify({ a: 1, b: 2 });
      fetch(url, {
        method: "post",
        body: dataStr,
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((res) => res.json())
        .then((res) => console.log(res))
        .catch((error) => console.log(error));
    }
  </script>

 axios

<button type="button" onclick="axiosFormSerialize('form')">axios form serialize</button>
<button type="button" onclick="axiosFormData('form')">axios formdata</button>
<button type="button" onclick="axiosJson()">axios json</button>
  <script>
    function axiosFormSerialize(domId) {
      const serializeData = $("#" + domId).serialize();
      axios({
        method: "post",
        url: url,
        data: serializeData,
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
      })
        .then((response) => {
          if (response.status == "200") {
            console.log(response.data);
          }
        })
        .catch((error) => console.log(error));
    }

    function axiosFormData(domId) {
      const formData = new FormData(document.getElementById(domId));
      axios({
        method: "post",
        url: url,
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
      })
        .then((response) => {
          if (response.status == "200") {
            console.log(response.data);
          }
        })
        .catch((error) => console.log(error));
    }

    function axiosJson() {
      axios({
        method: "post",
        url: url,
        data: dataObj,
      })
        .then((response) => {
          if (response.status == "200") {
            console.log(response.data);
          }
        })
        .catch((error) => {
          if (error.response) {
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
          } else if (error.request) {
            console.log(error.request);
          } else {
            console.log("Error", error.message);
          }
        });
    }
  </script>

 

posted @   carol2014  阅读(129)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示