Fetch(原生)的简单使用

前言: Fetch 提供了对 Request 和 Response 等对象通用的定义。 
发送请求或者获取资源,需要使用 fetch() 方法。

具体使用代码:

<script>  
    fetch("地址",{method:"请求方式"}).then(function (res) {    //将异步数据res处理成text(转成json),
        res.text().then(function (value) { 
            console.log(value);
        })
    })
</script>

示例:

get请求:

            fetch("url", {
                method: "get"
            }).then(function(resp) {
                //将服务器响应回来的内容 序列化成 json格式 使用text()也可以
                resp.json().then((data) => {
                    // data -> 数据
                })
            });

post请求:

            var arr1 = [{
                    name: "天皇盖地虎",
                    detail:"宝塔镇河妖"
                }];
fetch(
"url", { method: "post", headers: {//设置请求的头部信息 "Content-Type": "application/json" //跨域时可能要加上 //"Accept":"allication/json" }, //将arr1对象序列化成json字符串 body: JSON.stringify(arr1)//向服务端传入json数据 }).then(function(resp) { resp.json().then((data) => { }) });
原文地址:https://www.cnblogs.com/oukele/p/9464874.html