fetch的使用說明

1.RN官方文檔中,可以使用XMLHttpRequestphp

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
web

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中的數據提交失敗,那麼你可能須要把數據轉換成以下的表單提交的格式:json

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) {app

    if (res.ok) {post

        res.json().then(function(obj) {fetch

            // 這樣數據就轉換成json格式的了url

        })code

    }orm

}, 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); 

  });

參考文檔:https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch
相關文章
相關標籤/搜索