ajax request and fetch request

ajax

1 is an example of XMLHTTPRequest

2. Only when the status is successful request will be 200 or 304

3. Format fragmented, prone to problems callback hell

fetch

1.fetch promise is based on the realization, it can also be combined async / await

2.fetch request with the cookie default is not necessary to provide fetch (URL, {credentials: 'include'}). 

Credentials There are three parameters: same-origin, include, *

3. When the server returns a status code 400 500 and will not reject, only lead to a network error request can not be completed, fetch will be reject

4. IE not support all versions of native Fetch

5.fetch is a method widow of

 

A simple example:

FETCH (URL) .then (function (Response) { 
    return response.json () // first step executed successfully 
}). the then (function (returnedValue) { 
    // perform a successful second step 
}). catch (function ( ERR) { 
    // error anywhere in the middle will be captured here 
})

Note:
the second parameter fetch in
a default request is a get request can use method: post for configuration 
2, the first step there are many ways in response JSON () text () formData ()
. 3, the cross-domain the Fetch the default cookie will not take the time to manually specify the credentials: 'include'

Obtained after the use of fetch is when a promise object inside the object and then define this promise to perform a successful Yes. Here is the correct way to use fetch the

 var promise=fetch('http://localhost:3000/news', {
        method: 'get'
    }).then(function(response) {
             return  response.json()
    }).catch(function(err) {
        // Error :(
    });
    promise.then(function (data) {
          console.log(data)
    }).catch(function (error) {
        console.log(error)
    })
//练习一, 使用get 和post方式获取数据

//将事件放在组件外部
function getRequest(url) {
    var opts = {
        method:"GET"
    }
    fetch(url,opts)
        .then((response) => {
            return response.text();  //返回一个带有文本的对象
        })
        .then((responseText) => {
            alert(responseText)
        })
        .catch((error) => {
            alert(error)
        })

}
//Post方法, 需要请求体body
/*
* FromData
* 主要用于序列化表单以及创建与表单格式相同的数据
*
* var data = new FormData();
* data.append("name","hello");
* append方法接收两个参数,键和值(key,value),分别表示表单字段的名字 和 字段的值,可添加多个
*
* 在jQuery中,"key1=value1&key2=valu2" 作为参数传入对象框架,会自动分装成FormData形式
* 在Fetch 中,进行post进行post请求,需要自动创建FormData对象传给body
*
* */
function postRequest(url) {
    //将"key1=value1&key2=valu2" 形式封装整FromData形式
    let formData = new FormData();
    formData.append("username","hello");
    formData.append("password","1111aaaa");

    var opts = {
        method:"POST",   //请求方法
        body:formData,   //请求体
     headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },

    }

    fetch(url,opts)
        .then((response) => {
//你可以在这个时候将Promise对象转换成json对象:response.json()
    //转换成json对象后return,给下一步的.then处理
            return response.text
        })
        .then((responseText) => {
            alert(responseText)
        })
        .catch((error) => {
            alert(error)
        })
}

fetch和ajax 的主要区别

1、fetch()返回的promise将不会拒绝http的错误状态,即使响应是一个HTTP 404或者500 
2、在默认情况下 fetch不会接受或者发送cookies

使用fetch开发项目的时候的问题

1、所有的IE浏览器都不会支持 fetch()方法
2、服务器端返回 状态码 400 500的时候 不会reject

 

Guess you like

Origin www.cnblogs.com/baixiaoxiao/p/11302814.html