侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 130562 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

Javacript 基于Promise的fetch网络请求

2024-05-13 星期一 / 0 评论 / 0 点赞 / 88 阅读 / 3834 字

一,常见Ajax网络请求 我们常见的网络Ajax请求如下。 function search(term, onload, onerror) { var xhr, results, url; url

一,常见Ajax网络请求

我们常见的网络Ajax请求如下。

function search(term, onload, onerror) {  var xhr, results, url;  url = 'http://example.com/search?q=' + term;  xhr = new XMLHttpRequest();  xhr.open('GET', url, true);  xhr.onload = function (e) {    if (this.status === 200) {      results = JSON.parse(this.responseText);      onload(results);    }  };  xhr.onerror = function (e) {    onerror(e);  };  xhr.send();}search("Hello World", console.log, console.error);

二、基于Promise的网络请求

如果使用Promise范式编程,那么我们需要如下编写处理流程

(具体请参考:http://my.oschina.net/ososchina/blog/644334)

function search(term) {  var url = 'http://example.com/search?q=' + term;  var xhr = new XMLHttpRequest();  var result;  var p = new Promise(function (resolve, reject) {    xhr.open('GET', url, true);    xhr.onload = function (e) {      if (this.status === 200) {        result = JSON.parse(this.responseText);        resolve(result);      }    };    xhr.onerror = function (e) {      reject(e);    };    xhr.send();  });  return p;  

三、使用fetch+Request的请求

这是一项Google和火狐的测试技术,不是W3C标准技术,同样也不支持mobile。

fetch请求同样基于Promise范式,但是fetch为我们封装了Ajax请求,使用也非常方便,就像下面这个请求

var myHeaders = new Headers({  "Content-Type": "text/plain",  "X-Custom-Header": "ProcessThisImmediately" //使用自定义header});var myInit = { method: 'GET',               headers: myHeaders,               mode: 'cors',  //这里是跨域模式               cache: 'default' };fetch('flowers.jpg',myInit).then(function(response) {  if(response.ok) {    response.blob().then(function(myBlob) {      var objectURL = URL.createObjectURL(myBlob);      myImage.src = objectURL;    });  } else {    console.log('Network response was not ok.');  }}).then(function(myBlob) {  var objectURL = URL.createObjectURL(myBlob);}).catch(function(error) {  //捕获异常  console.log('请求发生异常: ' + error.message);});;

当然,如果你 不是真正处理网络请求,而是想把请求发送到ServiceWorker工作线程,那么ServiceWorker线程需要如下接收并处理你的请求

var myBody = new Blob();addEventListener('fetch', function(event) {  event.respondWith(new Response(myBody, {    headers: { "Content-Type" : "text/plain" }  });});

self.addEventListener('fetch', function(event) {  console.log('添加处理fetch时间获得相应', event.request.url);  event.respondWith(caches.match(event.request).then(function(response) { //匹配处理请求       if (response) {        console.log('缓存数据:', response);        return response;      }      console.log('No response found in cache. About to fetch from network...');      return fetch(event.request).then(function(response) {  //这里转发请求        console.log('响应数据:', response);        return response;      }).catch(function(error) {        console.error('获取数据失败:', error);        throw error;      });    })  );});

发送带有请求体的POST Request

fetch支持如下数据类型

ArrayBuffer,ArrayBufferView (Uint8Array and friends), Blob/File, string ,URLSearchParams ,FormData

比如我们POST数据

var form = new FormData(document.getElementById('login-form'));fetch("/login", {  method: "POST",  body: form}).then(function(resp) { }).catch(function(error) {  //捕获异常  console.log('请求发生异常: ' + error.message);});;

 

广告 广告

评论区