ES6 fetch函数与后台交互实现
2018-11-14 15:28
896 查看
最近在学习react-native,遇到调用后端接口的问题.看了看官方文档,推荐使用es6的fetch来与后端进行交互,在网上找了一些资料.在这里整理,方便以后查询.
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的原生方法,这里不做多的介绍.
2.RN官方文档中,推荐使用fetch
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) })
body中的数据就是我们需要向服务器提交的数据,比如用户名,密码等;如果上述body中的数据提交失败,那么你可能需要把数据转换成如下的表单提交的格式:
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格式的数据:
fetch('https://mywebsite.com/endpoint/').then(function(res) { if (res.ok) { res.json().then(function(obj) { // 这样数据就转换成json格式的了 }) } }, function(ex) { console.log(ex) })
fetch模拟表单提交:
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进行了一次封装,大家各取所好吧.
参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- ES6 fetch函数与后台交互
- (转载)ES6 fetch函数与后台交互
- ES6 fetch函数与后台交互
- ajax前后台交互入门例子实现控制台打印结果
- Echarts在JavaWeb中与后台的交互实现
- Ajax之前后台简单交互---登录实现
- web前端——ajax提交后台controller实现前端后台交互(2) 传两个参数 ,后台controller接收处理
- 如何用CropBox实现头像裁剪并与java后台交互
- 封装类DataProtocol 实现后台与页面的数据交互
- 玩转Web之Json(二)----jquery easy ui + Ajax +Json+SQL实现前后台数据交互
- android提供了几种常用的方式,用于实现后台线程与UI线程的交互
- php与ajax交互——实现php实时返回结果给ajax,并在后台保持继续运行的方法
- php与ajax交互——实现php实时返回结果给ajax,并在后台保持继续运行的方法
- 利用ajax提交表单,实现数据前端后台数据交互的完整流程演示
- react实现前后台数据交互
- 很全面的登陆注册界面实现,包括页面显示和后台数据库交互(写了我一下午)
- 玩转Web之Json(二)----jquery easy ui + Ajax +Json+SQL实现前后台数据交互
- AngularJS实现与后台服务器进行交互的示例讲解
- ASP.NET使用AjaxPro实现前端跟后台交互详解
- AirPrint: 无交互的后台打印实现(Print without UI,iOS8+)