【以查询垃圾分类为例】使用前端接口调用的几种方式(ajax,基于jquery的ajax,fetch,axios)

8 篇文章 0 订阅
2 篇文章 0 订阅

准备

1. 垃圾分类接口

查询垃圾分类的免费api

接口地址:https://api.66mz8.com/api/garbage.php
返回格式:json
请求方式:get/post
请求示例https://api.66mz8.com/api/garbage.php?name=纸巾
在这里插入图片描述

2. 准备html

在这里插入图片描述
查看效果 https://www.jq22.com/yanshi23274

  <div class="garbegeBox">
    <div class="bg1"></div>
    <div class="box">
      <h1 class="title">
        <i class="web-font">垃圾分类查询</i>
      </h1>
      <div id="garbegeSearchBox" class="garbegeSearchBox">
        <input type="text" class="searchInput">
        <button class="searchBtn"></button>
      </div>
      <div id="garbegeShowBox" class="garbegeShowBox">
        输入要查询的垃圾
      </div>
    </div>
  </div>

3. 准备node服务器

const http = require("http");
const fs = require("fs");
const url = require('url');
const path = require('path');
const mime = require('mime');

const app = http.createServer();

app.on('request', (req, res) => {
	//跨域
  res.setHeader("Access-Control-Allow-Credentials", "true");
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:8888");
  res.setHeader("Access-Control-Allow-Headers", "*");
  res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");


  // 获取用户的请求路径
  let pathname = url.parse(req.url).pathname;
  pathname = pathname == '/' ? '/index.html' : pathname;

  // 将用户的请求路径转换为实际的服务器硬盘路径
  let realPath = path.join(__dirname, 'public' + pathname);

  let type = mime.getType(realPath)

  // 读取文件
  fs.readFile(realPath, (error, result) => {

    // 如果文件读取失败
    if (error != null) {
      res.writeHead(404, {
        'content-type': 'text/html;charset=utf8'
      })
      res.end('文件读取失败');
      return;
    }
    res.writeHead(200, {
      'content-type': type
    })

    res.end(result);
  });
});
app.listen(8888);
console.log('服务器启动成功')

4. 接口调用方式

  • 基Promise的AJAX请求
  • 基于jQuery的ajax
  • fetch
  • axios

一、基于Promise的AJAX请求

  window.onload = function () {
      const searchINPUT = document.getElementsByClassName("searchInput");
      const searchBtn = document.getElementsByClassName("searchBtn");
      const showPanelParent = document.getElementById("garbegeShowBox");
      // console.log(searchINPUT,searchBtn,showPanelParent)
      
      searchBtn[0].onclick = function () {
        const _searchINPUT = searchINPUT[0].value;
        // console.log(_searchINPUT)
        let url = 'https://api.66mz8.com/api/garbage.php?name=' + _searchINPUT
        queryData(url, 'post').then(function (data) {
          // console.log(data)
          data = JSON.parse(data)
          if (_searchINPUT == '' || data.code == 201 || data.code == 202) {
            showPanelParent.innerHTML = data.msg
          }else{
            showPanelParent.innerHTML = data.name + ' : ' + data.data
          } 
        }, function (data) {
          console.log(data)
        })
      }

      // 基于Promise的ajax请求
      function queryData(url, method) {
        var p = new Promise(function (resolve, reject) {
          var xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function () {
            if (xhr.readyState != 4) return;
            if (xhr.readyState == 4 && xhr.status == 200) {
              resolve(xhr.responseText);
            } else {
              reject('服务器错误');
            }
          };
          xhr.open(method, url);
          xhr.send(null);
        })
        return p
      }
    }

效果:

二、基于jQuery的ajax

准备jQuery

 <script  src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
 <script>
    $(function () {
      $(".searchBtn").click(function () {
        $.ajax({
          url: "https://api.66mz8.com/api/garbage.php",
          type: "GET",
          data: "name="+$(".searchInput").val(),
          dataType: "json",
          success: function (data) {
            console.log(data)
            if($(".searchInput").val() =='' || data.code == 201 || data.code == 202){
              $(".garbegeShowBox").html(data.msg)
            }else if(data.code == 200){
              $(".garbegeShowBox").html(data.name+' : '+data.data)
            }           
          }
        });
      })
    })
  </script>

【参考文档】 https://jquery.cuishifeng.cn/jQuery.Ajax.html

三、fetch

  • Fetch API是新的ajax解决方案 Fetch会返回Promise
  • fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。
  • fetch(url,options).then()

    window.onload = function () {
      const searchINPUT = document.getElementsByClassName("searchInput");
      const searchBtn = document.getElementsByClassName("searchBtn");
      const showPanelParent = document.getElementById("garbegeShowBox");


      searchBtn[0].onclick = function () {

        const _searchINPUT = searchINPUT[0].value;
        const url = 'https://api.66mz8.com/api/garbage.php?name=' + _searchINPUT;

        fetch(url, {
          method: 'post',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          body: JSON.stringify({
            "name": _searchINPUT
          })
        }).then(res => {
          return res.json();
        }).then(json => {
          console.log('获取的结果', json, json.code, json.name, json.data);
          if (_searchINPUT == '' || json.code == 201 || json.code == 202) {
            showPanelParent.innerHTML = json.msg
          } else if(json.code == 200) {
            showPanelParent.innerHTML = json.name + ' : ' + json.data
          }
          return json;
        }).catch(err => {
          console.log('请求错误', err);
        })
      }
    }

【参考文档】https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

四、axios

  • 基于promise
  • 用于浏览器和node.js的http客户端
  • 支持浏览器和node.js
  • 支持promise 能拦截请求和响应
  • 自动转换JSON数据
  • 能转换请求和响应数据

引用 axios.js

https://cdn.bootcdn.net/ajax/libs/axios/0.20.0/axios.min.js

  <script>
    const searchINPUT = document.getElementsByClassName("searchInput");
    const searchBtn = document.getElementsByClassName("searchBtn");
    const showPanelParent = document.getElementById("garbegeShowBox");
    
    searchBtn[0].onclick = function () {
      const _searchINPUT = searchINPUT[0].value;
      const url = 'https://api.66mz8.com/api/garbage.php?name=' + _searchINPUT;

      axios.get(url).then(function (ret) {
        // 注意data属性是固定的用法,用于获取后台的实际数据
        // console.log(ret.data)
        const data = ret.data
        if (_searchINPUT == '' || data.code == 201 || data.code == 202) {
          showPanelParent.innerHTML = data.msg
        } else if (data.code == 200) {
          showPanelParent.innerHTML = data.name + ' : ' + data.data
        }
      })
    }
  </script>

【参考文档】http://axios-js.com/zh-cn/docs/

涉及到的跨域问题

在node中设置响应头来跨域

“Access-Control-Allow-Origin”, " * "
Access-Control-Allow-Credentials", “true”
Access-Control-Allow-Methods",“PUT,POST,GET,DELETE,OPTIONS”

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起伏羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值