zoukankan      html  css  js  c++  java
  • fetch皮毛

    fetch概述

    1.基本特性

    • ​ 更加简单的数据获取方式,功能更强大,更灵活,可以看做是xhr的升级版
    • ​ 基于Promise实现

    2.语法结构

    fetch(url).then(fn2)
        .then(fn3)
        ...
        .catch(fn)
    
    fetch('/abc').then(data=>{
        return data.text();
    }).then(ret=>{
        //注意这里得到的才是最终的数据
        console.log(ret);
    })
    //(text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据)
    
    

    fetch请求参数

    1.常用配置选项

    methods(String):HTTP请求方法,默认为GET(GET、POST、PUT、DELETE)

    body(String):HTTP的请求参数

    headers(Object):HTTP的请求头,默认为{}

    fetch('/abc',{
        method:'get'
    }).then(data=>{
        return data.text();
    }).then(ret=>{
        //注意这里的到的才是最终的数据
        console.log(ret);
    });
    

    2.get请求方式的参数传递

    fetch('/abc?id=123').then(data=>{
        return data.text();
    }).then(ret=>{
         //注意这里的到的才是最终的数据
        console.log(ret);
    })
    
     fetch('/abc/123',{
        method:'get'
    }).then(data=>{
        return data.text();
    }).then(ret=>{
        //注意这里的到的才是最终的数据
        console.log(ret);
    });
    

    3.DELETE请求方式的参数传递

    fetch('/abc/123',{
        method:'delete'
    }).then(data=>{
        return data.text();
    }).then(ret=>{
        //注意这里的到的才是最终的数据
        console.log(ret);
    })
    

    4.POST请求方式的参数传递

    fetch('/books',{
        method:'post',
        body:'uname=lisi&pwd=123',
        headers:{
            'Content-Type':'application/x-www-form-urlencoded',
        }
    }).than(data=>{
        return data.text();
    }).then(ret=>{
        console.log(ret);
    })
    
    fetch('/books',{
        method:'post',
        body:JSON.stringfy({
            uname:'lisi',
            age:12
        })
        headers:{
        	'Content-Type':'application/json',
    	}
    }).then(data=>{
        return data.text();
    }).then(ret=>{
        console.log(ret);
    })
    

    5.PUT请求方式的参数传递

    fetch('/books/123',{
        method:'put',
        body:JSON.stringfy({
            uname:'lisi',
            age:12
        })
        headers:{
        	'Content-Type':'application/json',
    	}
    }).then(data=>{
        return data.text();
    }).then(ret=>{
        console.log(ret);
    })
    

    fetch响应结果

    响应数据格式

    ​ text():将返回体处理成字符串类型

    ​ json():将返回结果和JSON.parse(responseText)一样

    fetch('/data' then(data)=>{
        //return data.text();
        return data.json();
    }).then(ret=>{
        console.log(ret);
    })
    

  • 相关阅读:
    FileChannel的基本使用
    qq在线交流
    ci框架连接数据库
    绩效管理,如何实现“投资于人”?
    Asp.Net开发中传递的URL的长度问题
    ASP.NET程序中常用的三十三种代码
    认识ASP.NET配置文件Web.config
    JS实现图片幻灯片效果
    一些web开发中常用的、做成cs文件的js代码
    div自适应浏览器高度的问题
  • 原文地址:https://www.cnblogs.com/wahaha-/p/14051096.html
Copyright © 2011-2022 走看看