ES6 fetch函数与后台交互
2016-06-07 14:42
387 查看
最近在学习react-native,遇到调用后端接口的问题.看了看官方文档,推荐使用es6的fetch来与后端进行交互,在网上找了一些资料.在这里整理,方便以后查询.
1.RN官方文档中,可使用XMLHttpRequest
'
fetch模拟表单提交:
不过无论是ajax还是fetch,都是对http进行了一次封装,大家各取所好吧.
参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch
1.RN官方文档中,可使用XMLHttpRequest
varrequest=newXMLHttpRequest();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格式的数据:[code]'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(
'RequestsucceededwithJSONresponse'
,data);
})
.
catch
(
function
(error){
console.log(
'Requestfailed'
,error);
});
不过无论是ajax还是fetch,都是对http进行了一次封装,大家各取所好吧.
参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch
相关文章推荐
- JavaScript(js)对象常用操作,JS操作JSON总结
- jsp指令中的taglib指令
- servlet跳转进入jsp中,C标签<c:url>不能生效之谜
- 在JavaScript ES6中使用let和const定义变量
- Knockoutjs 学习系列(二)花式捆绑
- 1、考虑用静态工厂方法代替构造器(effective java)
- RAC那些干货——3
- 零基础入门-javaScript学习笔记之变量和作用域
- 关于html语言中的元素标签有哪些是直接闭合的</>,而不是成对出现
- error sass/styles.scss (Line 4: Invalid CSS after "銆€銆€": expected "{", wa s "}")
- Bootstrap模态框(modal)垂直居中
- 零基础入门-javaScript学习笔记之从基本数据类型学起
- jsp指令的include指令
- block,inline和inline-block概念和区别
- Code笔记之:CSS块级元素、内联元素概念
- Code笔记之:CSS+HTML display 属性
- jstl标签<c:forEach>如何获取循环子级元素值
- HTML5 video 和 audio
- json 转list 集合数组
- Knockoutjs 学习系列(一)ko初体验