Fetch API

ECMAScript6新特性【Fetch API (POST请求注意事项)、Fetch网络请求应用、封装Fetch网络请求、Class 的基本语法】(十)-全面详解(学习总结---从入门到深化)_ecmascript

 fetch() 是 XMLHttpRequest 的升级版,用于在 JavaScript 脚本里面 发出 HTTP 请求 浏览器原生提供这个对象

fetch() 的功能与 XMLHttpRequest 基本相同,但有三个主要的差异

1、fetch() 使用 Promise,不使用回调函数,因此大大简化了写法,写起来更简洁

2、fetch() 采用模块化设计,API 分散在多个对象上(Response 对象、Request 对象、Headers 对 象),更合理一些;相比之下,XMLHttpRequest 的 API 设计并不是很好,输入、输出、状态都在同一个接口管理,容易写出非常混乱的代码

3、fetch() 通过数据流(Stream 对象)处理数据,可以分块读取,有利于提高网站性能表现,减少内 存占用,对于请求大文件或者网速慢的场景相当有用。XMLHTTPRequest 对象不支持数据流,所 有的数据必须放在缓存里,不支持分块读取,必须等待全部拿到后,再一次性吐出来

 基本用法

fetch() 接受一个 URL 字符串作为参数,默认向该网址发出 GET 请 求,返回一个 Promise 对象

fetch(url)
 .then(...)
 .catch(...)

完整网络请求

fetch('http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php')
   .then(response => response.json())
   .then(json => console.log(json))
   .catch(err => console.log('RequestFailed', err));

支持的请求参数

fetch("http://iwenwiki.com/api/blueberrypai/
login.php", {
    method: "POST",
    headers: {
        "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
   },
    body: "user_id=iwen@qq.com&password=iwen123&verification_code=crfvw"
}).then(res => {
    return res.json()
}).then(data => {
    console.log(data);
})

实时效果反馈

1. 下列代码,划横线处应该填写的代码是:

fetch("http://iwenwiki.com/api/blueberrypai/login.php", { ___: "POST", headers: { "Content-type": "application/x-wwwform-urlencoded; charset=UTF-8", }, body: "user_id=iwen@qq.com&password=iwen123&verification_code=crfvw" }).then(res => { return res.json() }).then(data => { console.log(data); })

A type

B method

C post

D get

Fetch API POST请求注意事项

ECMAScript6新特性【Fetch API (POST请求注意事项)、Fetch网络请求应用、封装Fetch网络请求、Class 的基本语法】(十)-全面详解(学习总结---从入门到深化)_php_02

 Fetch

function myFetch(url, data) {
    return new Promise((resolve, reject) =>
    {
        fetch(url, {
            method: "POST",
            headers: {
                "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
           },
            body: formator(data)
       }).then(res => {
            return res.json()
       }).then(data => {
            resolve(data)
       },error =>{
            reject(error)
       })
   })
}
function formator(data) {
    var dataStr =""
    Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] +'&';
   })
    if (dataStr !== '') {
        dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
   }
    return dataStr;
}
myFetch("http://iwenwiki.com/api/blueberrypai/login.php", {
    user_id: "iwen@qq.com",
    password: "iwen123",
    verification_code: "crfvw"
}).then(data =>{
    console.log(data);
})

实时效果反馈

1. 下列代码,划横线处应该填写的代码是:

function formator(data) { var dataStr ="" Object.keys(data).forEach(key => { dataStr += key + '=' + data[key] + '&'; }) if (dataStr !== '') { dataStr = dataStr.___(0,dataStr.lastIndexOf('&')); } return dataStr; }

A substr

B charAt

C indexOf

D trim

Fetch网络请求应用 

ECMAScript6新特性【Fetch API (POST请求注意事项)、Fetch网络请求应用、封装Fetch网络请求、Class 的基本语法】(十)-全面详解(学习总结---从入门到深化)_php_03

fetch 与 promise

function ajax(url) {
    return new Promise(function (resolve,reject) {
        fetch(url).then(data => {
            return data.json()
       }).then(data =>{
            resolve(data)
       },error =>{
            reject(error)
       })
   })
}
async function getInfo() {
    let ids = await ajax("http://iwenwiki.com/api/generator/list.php")
    let names = await ajax("http://iwenwiki.com/api/generator/id.php?id=" + ids[0])
    let infos = await ajax("http://iwenwiki.com/api/generator/name.php?name=" + names.name)
    return infos
}
getInfo().then(res =>{
    console.log(res);
},error =>{
    console.log(error);
})

封装Fetch网络请求

ECMAScript6新特性【Fetch API (POST请求注意事项)、Fetch网络请求应用、封装Fetch网络请求、Class 的基本语法】(十)-全面详解(学习总结---从入门到深化)_ecmascript_04

为了日后使用方便,可以对 fetch 进行封装 

function formator(data) {
    var dataStr = ""
    Object.keys(data).forEach(key => {
        dataStr += key + '=' + data[key] + '&';
   })
    if (dataStr !== '') {
        dataStr = dataStr.substr(0,dataStr.lastIndexOf('&'));
   }
    return dataStr;
}
async function ajax(url = '', data = {},type = 'GET') {
    if (type == 'GET') {
        var dataStr = formator(data)
        url = url + '?' + dataStr;
   }
    let requestConfig = {
        method: type,
        headers: {
            "Content-type": "application/xwww-form-urlencoded; charset=UTF-8"
       }
   }
    if (type == 'POST') {
            Object.defineProperty(requestConfig,'body', {
            value: formator(data)
       })
   }
    const response = await fetch(url,requestConfig);
    const responseJson = await response.json();
    return responseJson
}
ajax("http://iwenwiki.com/api/blueberrypai/login.php", {
    user_id: "iwen@qq.com",
    password: "iwen123",
    verification_code: "crfvw"
},"POST").then(data =>{
    console.log(data);
})
ajax("http://iwenwiki.com/api/generator/list.php").then(data =>{
    console.log(data);
})

Class 的基本语法

ECMAScript6新特性【Fetch API (POST请求注意事项)、Fetch网络请求应用、封装Fetch网络请求、Class 的基本语法】(十)-全面详解(学习总结---从入门到深化)_php_05

类的由来 

JavaScript 语言中,生成实例对象的传统方法是通过构造函数

function Point(x, y) {
  this.x = x;
  this.y = y;
}
Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);

class

基本上,ES6 的 class 可以看作只是一个语法糖,它的绝大部分功 能,ES5 都可以做到,新的 class

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
 }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
 }
}

constructor 方法

constructor() 方法是类的默认方法,通过 new 命令生成对象实例时,自动调用该方法。一个类必须有 constructor() 方法,如果没有显式定义, 一个空的 constructor() 方法会被默认添加

class Point {
}
// 等同于
class Point {
  constructor() {}
}

 类的实例

生成类的实例的写法,与 ES5 完全一样,也是使用 new

class Point {
  // ...
}
// 报错
var point = Point(2, 3);
// 正确
var point = new Point(2, 3);

 取值函数(getter)和存值函数(setter)

class Person {
    constructor(name) {
        this.name = name;
   }
    get n() {
        return this.name
   }
    set n(value) {
        this.name = value;
   }
}
var p = new Person("iwen")
console.log(p.n);
p.n = "ime"
console.log(p.n);

注意点

严格模式

类和模块的内部,默认就是严格模式,所以不需要使用 use strict 指定 运行模式。只要你的代码写在类或模块之中,就只有严格模式可 用。考虑到未来所有的代码,其实都是运行在模块之中,所以 ES6 实际上把整个语言升级到了严格模式

不存在提升

类不存在变量提升(hoist),这一点与 ES5 完全不同

new Foo(); // ReferenceError
class Foo {}

name 属性

由于本质上,ES6 的类只是 ES5 的构造函数的一层包装,所以函数 的许多特性都被 Class 继承,包括 name

class Point {}
Point.name // "Point"

 实时效果反馈

1. 下列代码,运行结果是什么:

class Person {
    constructor(name) {
        this.name = name;
   }
    get n() {
        return this.name
   }
    set n(value) {
        this.name = value;
   }
}
var p = new Person("sxt")
p.n = "itxiaotong"
console.log(p.n);
A sxt
B itbaizhan
C null
D undefined