zoukankan      html  css  js  c++  java
  • Fetch的使用

    基本特性:

    更加简单的数据获取方式,功能更强大,更灵活,可以看做是xhr的升级版

    使用

    1   fetch('url').then(function(data){
    2 return data.text()
    3         }).then(function(data){
    4 console.log(data);
    5         })

    其中text()属于fetchAPI的一部分,并且返回一个promise实列对象 ,用于获取后台返回的对象

    fetch请求参数

    method(string):http请求方法,默认为get(get,post,delete,put)

    body(string):http请求参数

    headers(object):http请求头,默认为0

    发起get请求

    1 fetch('url', {
    2             method: 'get'//其实get请求时这个可以不写,因为默认为get请求
    3         }
    4         ).then(function (data) {
    5             return data.text()
    6         }).then(function (data) {
    7             console.log(data);
    8         })

    delete请求

    1  fetch('url',{
    2             method:'delete'
    3         }).then(function(data){
    4 return data.text()
    5         }).then(function(data){
    6 console.log(data);
    7         })

    post请求

     1 fetch('url', {
     2             method: 'post',
     3             body: 'name=lisi&age=14',//用于传递参数
     4             headers: {
     5                 'Content-Type': 'application/x-www-form-urlencoded '//表明数据格式必须写
     6             }.then(function (data) {
     7                 return data.text()
     8             }).then(function (data) {
     9                 console.log(data);
    10             })
    11         })

    put与post同理

    响应数据格式

    text()将返回的数据处理成字符串

    json()返回结果和JSON.parse()一样

  • 相关阅读:
    博客园代码
    前端
    1338. Reduce Array Size to The Half
    1220. Count Vowels Permutation
    363. Max Sum of Rectangle No Larger Than K
    366. Find Leaves of Binary Tree
    443. String Compression
    8 · Rotate String
    886. Possible Bipartition
    LT 183 wood cut
  • 原文地址:https://www.cnblogs.com/xiaopo/p/14335380.html
Copyright © 2011-2022 走看看