AJax之Fetch

来源:互联网 发布:小说地图生成软件 编辑:程序博客网 时间:2024/06/03 19:22

简单的fetching示例

在Fetch API中,最常用的就是fetch()函数。它接收一个URL参数,返回一个promise来处理response。response参数带着一个Response对象。

fetch("/data.json").then(function(res) {  // res instanceof Response == true.  if (res.ok) {    res.json().then(function(data) {      console.log(data.entries);    });  } else {    console.log("Looks like the response wasn't perfect, got status", res.status);  }}, function(e) {  console.log("Fetch failed!", e);});

如果是提交一个POST请求,代码如下:

fetch("http://www.example.org/submit.php", {  method: "POST",  headers: {    "Content-Type": "application/x-www-form-urlencoded"  },  body: "firstName=Nikhil&favColor=blue&password=easytoguess"}).then(function(res) {  if (res.ok) {    alert("Perfect! Your settings are saved.");  } else if (res.status == 401) {    alert("Oops! You are not authorized.");  }}, function(e) {  alert("Error submitting form!");});
  <script>    var result = fetch('https://api.github.com')    result.then(function(response) {      console.log('response', response)      console.log('header', response.headers.get('Content-Type'))      return response.text()    }).then(function(text) {      console.log('got text', text)    }).catch(function(ex) {      console.log('failed', ex)    })  </script>

兼容浏览器处理

if(self.fetch) {    // 使用 fetch 框架处理} else {    // 使用 XMLHttpRequest 或者其他封装框架处理}

一般的请求方法

使用 fetch 的构造函数请求数据后,返回一个 Promise 对象,处理即可

fetch("http://blog.parryqiu.com").then(function(response){   // do something...})
0 0
原创粉丝点击