首页 > 其他分享 >js网络请求插件和FormData简单使用

js网络请求插件和FormData简单使用

时间:2022-11-19 10:15:02浏览次数:53  
标签:function 插件 console log url res FormData js formData

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link href="./plugins/bootstrap-5.1.3-dist/css/bootstrap.min.css" rel="stylesheet" />
    <script src="./plugins/jquery/jquery-1.9.1.js"></script>
    <script src="./plugins/axios.min.js"></script>
  </head>
  <body>
    <div class="mt-3 ms-3">
      <button type="button" class="btn btn-primary" value="2" onclick="func('exportArea',this,event)">onclick事件的this和event</button>
      <button type="button" class="btn btn-primary" value="2" onclick="func('exportArea')">onclick事件的this和event</button>
      <button type="button" class="btn btn-primary" value="2" id="btn3">onclick事件的this和event</button>
      <button type="button" class="btn btn-primary" value="2" id="btn1">jquery click事件的this和event</button>
      <button type="button" class="btn btn-primary" value="2" id="btn2">jquery click事件的this和event</button>
    </div>
    <div class="mt-3 ms-3">
      <form id="form1">
        <input type="text" name="aa" />
        <input type="file" name="file" />
        <button type="button" onclick="submitForm1('form1')" class="btn btn-primary">jquery ajax</button>
        <button type="button" onclick="submitForm2('form1')" class="btn btn-primary">fetch</button>
        <button type="button" onclick="submitForm3('form1')" class="btn btn-primary">axios</button>
        <br />
        <button type="button" onclick="getFormData('form1')" class="btn btn-primary">get form data</button>
        <button type="button" onclick="requestWithJson()" class="btn btn-primary">request with json</button>
        <button type="button" onclick="axiosRequest()" class="btn btn-primary">axios request</button>
      </form>
    </div>
  </body>
  <script>
    function func(param, dom, e) {
      console.log(param);
      console.log(dom);
      console.log(e);
    }

    document.querySelector("#btn3").addEventListener("click", function (e) {
      console.log(this);
      console.log(e);
    });

    $("#btn1").on("click", function (e) {
      console.log(this);
      console.log(e);
    });
    $("#btn2").on("click", (e) => {
      console.log(this);
      console.log(e);
    });
  </script>

  <script>
    function getFormData(domId) {
      // const formData = new FormData();
      const formData = new FormData(document.getElementById(domId));

      formData.append("k1", "v1");
      formData.append("k1", "v2");
      formData.append("k1", "v1");
      console.log(formData.get("k1"));
      console.log(formData.getAll("k1"));
      formData.append("k1", "v1");
      formData.set("k1", "1");
      console.log(formData.getAll("k1"));

      console.log(formData.has("k1"));
      formData.delete("k1");
      console.log(formData.has("k1"));

      //遍历
      for (let [index, item] of formData.entries()) {
        console.log(index, item);
      }
      console.log($("#" + domId).serialize());
    }
  </script>

  <script>
    function submitForm1(domId) {
      const serializeData = $("#" + domId).serialize();
      const url = "http://localhost/request.php";

      $.ajax({
        url: url,
        type: "post",
        cache: false,
        data: serializeData,
        dataType: "json",
        processData: false,
        contentType: "application/x-www-form-urlencoded",
        success: function (res) {
          console.log(res);
        },
        beforeSend: function () {},
        error: function () {},
      });

      const formData = new FormData(document.getElementById(domId));
      $.ajax({
        url: url,
        type: "post",
        cache: false,
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        success: function (res) {
          console.log(res);
        },
        beforeSend: function () {},
        error: function () {},
      });
    }

    function submitForm2(domId) {
      const url = "http://localhost/request.php";

      const serializeData = $("#" + domId).serialize();
      fetch(url, {
        method: "post",
        body: serializeData,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      })
        .then((res) => res.json())
        .then((res) => {
          console.log(res);
        });

      const formData = new FormData(document.getElementById(domId));
      fetch(url, {
        method: "post",
        body: formData,
      })
        .then((res) => res.json())
        .then((res) => {
          console.log(res);
        });
    }

    function submitForm3(domId) {
      const serializeData = $("#" + domId).serialize();
      const url = "http://localhost/request.php";

      axios
        .post(url, serializeData, {
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
        })
        .then((response) => {
          if (response.status == "200") {
            console.log(response.data);
          }
        });

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

  <script>
    function requestWithJson() {
      const dataObj = { a: 1, b: 2 };
      const dataStr = JSON.stringify({ a: 1, b: 2 });
      const url = "http://localhost/request.php";
      $.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 () {},
      });

      fetch(url, {
        method: "post",
        body: dataStr,
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((res) => res.json())
        .then((res) => {
          console.log(res);
        });

      axios.post(url, dataObj).then((response) => {
        if (response.status == "200") {
          console.log(response.data);
        }
      });
    }

    function axiosRequest() {
      const url = "http://localhost/request.php";

      // 发送 POST 请求
      axios({
        method: "post",
        url: url,
        data: {
          firstName: "Fred",
          lastName: "Flintstone",
        },
      });

      axios({
        method: "get",
        url: url,
        params: {
          p: 1,
        },
        data: {
          firstName: "Fred",
          lastName: "Flintstone",
        },
      });

      axios.get(url).catch(function (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);
        }
        console.log(error.config);
      });
    }
  </script>
</html>
 

 

标签:function,插件,console,log,url,res,FormData,js,formData
From: https://www.cnblogs.com/caroline2016/p/16905518.html

相关文章

  • html生成pdf的js插件的简单使用
    <!DOCTYPEhtml><html><head><metacharset="utf-8"/><title>jspdf</title><linkhref="./plugins/bootstrap-5.1.3-dist/css/bootstrap.min.css"re......
  • vba解析JSON字符串
    vba解析JSON字符串vba解析JSON大概有4种方法1、htmlfile对象解析json(支持32位和64位系统)思路:创建htmlfile对象,使用write方法写入浏览器版本,创建parentwindow对象,在使用e......
  • js树形组件zTree简单使用
    <!DOCTYPEhtml><html><head><title>ZTREEDEMO</title><metahttp-equiv="content-type"content="text/html;charset=UTF-8"/><linkrel="stylesh......
  • layer和sweetalert2消息提醒js插件简单使用
    <!DOCTYPEhtml><htmllang="en"backgound=""><head><metacharset="UTF-8"/><metahttp-equiv="X-UA-Compatible"content="IE=edge"/><metaname......
  • Vue中使用Mock,devSever中before方法弃用>webpack新版本出现的vue.config.js配置问题:op
    话不多说直接上代码:1、mock相关配置(mock/index.js),这里仅使用 setupMiddlewares其余旧版级过渡版本方法见官网1//引入mock2constMock=require('mockjs');......
  • Vue.js -- 条件渲染
    条件渲染v-if的用法代码演示:<head><title>vue条件渲染</title><!--使用CDN引入Vue--><scriptsrc="https://unpkg.com/vue@next"></script></head><b......
  • simpread-(132 条消息) three.js 加载 stl 文件并解析_攻城狮 plus 的博客 - CSDN 博
    threejs加载STL文件效果:加载stl格式的文件需要设置材质material;stl、obj都是静态模型,不可以包含动画,fbx除了包含几何、材质信息,可以存储骨骼动画等数据。代码:......
  • js Blob 与 ArrayBuffer
    1/*2*Blob3*4*Blob(BinaryLargeObject)表示二进制类型的大对象,在数据库管理系统中,将二进制数据存储为一个单一个体的集合5*Blob通常是影像、......
  • JS 选项卡
    思路:需要标题和页面内容两个部分,几个标题就对应几个页面,页面设置定位使其重叠,在美化一下css样式即可当点击某个标题时,显示出与标题相关的内容,同时标题样式发生变化,然后关......
  • nodejs.01
    fs模块导入fs模块,来操作文件constfs=require('fs');调用fs.readFile()方法读取文件参数1:读取文件存放路径参数2:读取文件时候采用的编码格式,一般默认utf-8参......