(转载)ES6 fetch函数与后台交互
来源:互联网 发布:雨人医药软件 编辑:程序博客网 时间:2024/06/09 22:05
http://www.cnblogs.com/Ricky-Huang/p/5566918.html
ES6 fetch函数与后台交互
最近在学习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){
body中的数据就是我们需要向服务器提交的数据,比如用户名,密码等;如果上述body中的数据提交失败,那么你可能需要把数据转换成如下的表单提交的格式:
console.log(res)
})
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);
});
- (转载)ES6 fetch函数与后台交互
- ES6 fetch函数与后台交互
- 后台函数与Javascript交互(非AJAX)
- AS3与后台交互
- ajax与后台交互
- extjs与后台交互
- jQuery 与后台交互
- 与后台交互注意事项
- ajax与后台交互
- ajax与后台交互
- android与后台交互
- html与后台交互
- js与后台交互
- es6 fetch body格式
- 【转载】FETCH
- 与后台交互选择的交互方式
- AJAX如何与后台交互
- AJAX如何与后台交互
- 表体某个页签的字段名字怎么动态改变
- Linux下nfs+rpcbind实现服务器之间的文件共享(mount 挂载)
- 对ThreadLocal实现原理的一点思考
- git 使用
- 2017-11-3离线赛总结
- (转载)ES6 fetch函数与后台交互
- 数据结构预习栈和队列
- caffe-pspnet-ubuntu16.04-CUDA8.0-8G
- JavaSE———继承
- 算法提高 学霸的迷宫
- Maven查看JAR包的依赖关系
- 饿了么运维基础设施进化史
- xcode8中关于错误skipping input stream 0 0 0x0
- 通过NFS-Ganesha将Ceph导出为NFS