ES6 fetch函数与后台交互实现

最近在学习react-native,遇到调用后端接口的问题.看了看官方文档,推荐使用es6的fetch来与后端进行交互,在网上找了一些资料.在这里整理,方便之后查询.php

1.RN官方文档中,可以使用XMLHttpRequest前端

var request = new XMLHttpRequest();
request.onreadystatechange = (e) = >{
  if (request.readyState !== 4) {
    return;
  }
  if (request.status === 200) {
    console.log('success', request.responseText);
  } else {
    console.warn('error');
  }
};
request.open('GET', 'https://mywebsite.com/endpoint.php');
request.send();

这是http的原生方法,这里不作多的介绍.react

2.RN官方文档中,推荐使用fetches6

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
}).then(function(res) {  console.log(res)
})

前端全栈学习交流圈:866109386,面向1-3经验年前端开发人员,帮助突破技术瓶颈,提高思惟能力,群内有大量PDF可供自取,更有干货实战项目视频进群免费领取。web

body中的数据就是咱们须要向服务器提交的数据,好比用户名,密码等;若是上述body中的数据提交失败,那么你可能须要把数据转换成以下的表单提交的格式:ajax

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: 'key1=value1&key2=value2'
}).then(function(res) {
 
    console.log(res)
})

这样能够获取纯文本的返回数据. 若是你须要返回json格式的数据:json

fetch('https://mywebsite.com/endpoint/').then(function(res) {
 
  if (res.ok) {
 
    res.json().then(function(obj) {
 
      // 这样数据就转换成json格式的了
 
    })
 
  }
 
}, function(ex) {
  console.log(ex)
})

fetch模拟表单提交:后端

前端全栈学习交流圈:866109386,面向1-3经验年前端开发人员,帮助突破技术瓶颈,提高思惟能力,群内有大量PDF可供自取,更有干货实战项目视频进群免费领取。react-native

fetch('doAct.action', { 
 
  method: 'post', 
 
  headers: { 
 
   "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
 
  }, 
 
  body: 'foo=bar&lorem=ipsum'
 
 })
 
 .then(json) 
 
 .then(function (data) { 
 
  console.log('Request succeeded with JSON response', data); 
 
 }) 
 
 .catch(function (error) { 
 
  console.log('Request failed', error); 
 
 });

不过不管是ajax仍是fetch,都是对http进行了一次封装,你们各取所好吧.服务器

相关文章
相关标签/搜索