当前位置:   article > 正文

js方法--fetch_js fetch then

js fetch then

fetch()方法与XMLHttpRequest类似,fetch也可以发起ajax请求,但是与XMLHttpRequest不同的是,fetch方式使用Promise,相比较XMLHttpRequest更加的简洁。fetch是全局量window的一个方法.

fetch方法的then会接收一个Response实例,值得注意的是fetch方法的第二个then接收的才是后台传过来的真正的数据,一般第一个then对数据进行处理等。例如fetch处理JSON响应时 回调函数有一个json()方法,可以将原始数据转换为json对象

基本使用:

  1. fetch('test.json', { //url (必须), options (可选)
  2. method:'POST'
  3. })
  4. .then(function(res){
  5. return res.json();
  6. })
  7. .then(function(data){
  8. console.log(data)
  9. //{name: "test", sex: "nan"}
  10. })

url参数是必须要填写的,option可选,设置fetch调用时的Request对象,如method、headers等
比较常用的Request对象有:

  • method(String): HTTP请求方法,默认为GET
  • body(String): HTTP的请求参数
  • headers(Object): HTTP的请求头,默认为{}
  • credentials(String): 默认为omit,忽略的意思,也就是不带cookie;还有两个参数,same-origin,意思就是同源请求带cookie;include,表示无论跨域还是同源请求都会带cookie

GET请求:

  1. fetch('test.js?id=12') //get方式可直接在url后面传参
  2. .then(function(response){
  3. console.log(response)
  4. return response.json();
  5. })
  6. .then(function(data){
  7. console.log(data)
  8. })

POST请求:

  1. fetch('/api/getItems', {
  2. body: JSON.stringify(params), //json字符串和对象都可以,推荐使用json字符串,这样可以在控制台network里看到请求参数
  3. cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  4. credentials: 'include', // include, same-origin, *omit
  5. headers: {
  6. 'Content-Type': 'application/json'
  7. },
  8. method: 'POST'
  9. }).then(response => response.json()).then(res => {
  10. console.log(res)
  11. })

具体参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/938543
推荐阅读
相关标签
  

闽ICP备14008679号