JS进步之路程序员Java 核心技术

Fetch实现数据异步传输

2019-05-04  本文已影响7人  Qibing_Fang

大家有没有这样一种经历:在网站注册账号时明明没有提交数据,页面就提示我们输入的信息是否可用。
这个功能的实现使用的就是数据异步传输技术

一、Fetch VS Ajax

二、Fetch文档与教程地址

MDN

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

Github

https://github.com/github/fetch

三、 Fetch实例

这个实例是我之前写的一个项目中的,真实可用

// Fetch发送数据的地址,改地址可自定义,与实际页面的地址无关
const url = '/userHome';
fetch(url, {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
    },
    body: JSON.stringify({
        // 你想要发送到后台的数据,以对象形式发送
        key: value,
    })
})
    .then(function(response) {
        return response.json();
    })
    .then(function(myJson) {
         // 在这里你可以对后端返回的数据进行处理,当然还可以别的,例如操作DOM
        console.log(myJson);
    });

四、Fetch参数说明

return  response.json();
// 其中的response是第一个then的形参,可自定义。

五、完整实例(包括简单前后端的搭建及Fetch的使用)

目录结构:


image.png
1、前端 ==> Html、CSS、JavaScript
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title> Demo </title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="../public/css/bootstrap.min.css">
    <script src="../public/js/jquery-3.3.1.slim.min.js"></script>
    <script src="../public/js/popper.min.js"></script>
    <script src="../public/js/bootstrap.min.js"></script>
</head>

<body >

    <div class="container p-3 bg-secondary">
        <%- body %>
    </div>

    <script>

        const addBtn = document.getElementById('add');
        const ul = document.getElementById('list-username');

        addBtn.onclick = function(event){
            const username = document.getElementById('username').value;
            const url = '/index';
            fetch(url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({
                    username: username,
                })
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(myJson) {
                const newLi = `
                    <li class="list-group-item text-danger font-weight-bold" style="background:greenyellow">
                        ${myJson.msg}
                    </li>
                `;
                $('#list-username').prepend(newLi);
            });
            document.getElementById("username").value = '';
        };

    </script>

</body>

</html>

<div class="content bg-white">
    <ul id="list-username" class="list-group p-3">
        <li class="list-group-item text-danger font-weight-bold"> AAAAAAAAAAAA </li>
        <li class="list-group-item"> BBBBBBBBBBBB </li>
        <li class="list-group-item"> CCCCCCCCCCCC </li>
    </ul>
</div>

<div class="add">
    <input type="text" id="username" name="username" placeholder="请输入...">
    <input type="button" id="add" name="add" value="提交">
</div>
2、后端 ==> Node.js
const KoaRouter = require('koa-router');
const router = new KoaRouter();


router.get("/", async (ctx) => { //路由
    await ctx.render('index');  //
});

router.post("/index", async (ctx) => { //路由
    const username = ctx.request.body.username;
    ctx.body = {msg: username};
});


module.exports = router;
3、Gif演示 ==>
1556978142711.gif

六、源码地址

https://github.com/ShyGodB/Blog-Code

上一篇 下一篇

猜你喜欢

热点阅读