fetch函数以及在vue中的应用

fetch是新一代XMLHttpRequest的一种替代方案。无需安装其他库。可以在浏览器中直接提供其提供的api轻松与后台进行数据交互。
基本用法:(引入vue文件,复制下方代码)
fetch 不需要额外的安装什么东西,直接就可以使用

<div id="box">
        <button @click="handleClick()">click</button>
        <ul>
            <li v-for="data in datalist" :key="data.filmId">
                <img :src="data.poster" :alt="data.name">
                <h3>{{data.name}}</h3>
                <p>{{data.synopsis}}</p>
            </li>
        </ul>
    </div>
    <script type="text/javascript">
    	
        new Vue({
            el:"#box",
            data:{
                datalist:[]
            },
            methods: {
                handleClick(){
                    //fetch get
                    fetch("json/test.json?name=kerwin&age=100").then(res=>{
                        // console.log(res.json())
                        //拿到的是 状态码
                        // return a.text() // 文本格式
                        return res.json() //json格式
                    }).then(res=>{
                        console.log(res.data.films)
                        this.datalist = res.data.films
                    }).catch(err=>{
                        console.log(err)
                    })

                    //post body 安全,

                    /*
                        1. form 编码 ,name=kerwin&age=100
                        2. json 编码 ,"{name:'kerwin',age:100}"
                    */


                    //fetch post -1 
                    // fetch("json/test.json",{
                    //     method:"post",
                    //     headers:{
                    //         "Content‐Type": "application/x‐www‐form‐urlencoded"
                    //     },
                    //     body:"name=kerwin&age=100" //请求体
                    // }).then(res=>res.json()).then(res=>{
                    //     console.log(res)
                    // })

                    //fetch post-2
                    fetch("json/test.json",{
                        method:"post",
                        headers:{
                            "Content-Type":"application/json"
                        },
                        body:JSON.stringify({
                            name:"kerwin",
                            age:100
                        }) //请求体
                    }).then(res=>res.json()).then(res=>{
                        console.log(res)
                    })
                }
            },
        })
       /*
        // post-1
         fetch("**",{
             credentials:"include",
             method:'post',
             headers: {
                "Content‐Type": "application/x‐www‐form‐urlencoded"
             },
            body: "name=kerwin&age=100",
            
        }).then(res=>res.json()).then(res=>{console.log(res)});
      
        // post-2
         fetch("https://m.vip.com/server.html?rpc&method=pageCache&f=www&_=1563946036520",{
             method:'post',
             headers: {
                "Content‐Type": "application/json"
             },
             body: JSON.stringify({
                 name:"kerin",
                 age:100
             })
        }).then(res=>res.json()).then(res=>{console.log(res)});
       */

    </script>

注意:
1 fetch返回的是promise对象。所以fetch().then()第一个then里返回的并不是真正的数据。而是一个promise,所以我们需要通过链式操作第二个then()来获取真正的数据。

        2  fetch发送参数是通过body字段来实现的。body是fetch第二个参数的必选参数之一。params的参数如下

        method(String): HTTP请求方法,默认为GET
        body(String): HTTP的请求参数
        headers(Object): HTTP的请求头,默认为{}
        credentials(String): 默认为omit,忽略的意思,也就是不带cookie;还有两个参数,same-origin,意思就是同源请求带cookie;include,表示无论跨域还是同源请求都会带cookie

       3 body带的参数是一个序列化以后的字符串。类似 name="coc"&age=30.所以这里我们通过qs库进行了序列化。注意通过cdn引入qs后qs函数应该是Qs,Qs.stringify(data)

2 在vue中的使用:

fetch支持在vue环境中使用。这样通过ajax请求就无需通过安装axios依赖库来实现。
一个简单的fetch请求很简单,代码如下:

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

fetch请求的优点:
1.语法简洁,更加语义化
2.更加底层,提供的API丰富(request, response)
3.脱离了XHR,是ES规范里新的实现方式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值