//在React Native中,使用fetch實現網絡請求 /* fetch 是一個封裝程度更高的網絡API, 使用了Promise * Promise 是異步編程的一種解決方案 * Promise 對象表明一個異步操做,有三種狀態:Pending(進行中) Resolved(已完成) Rejected(已失效) * * Promise 實例生成之後,能夠分別制定'完成' 和'失敗'狀態的回調函數,實現方式:鏈式調用方法 * * 語法: * fetch(參數) * .then(完成的回調函數) * .catch(失敗的回調函數) * * fetch(url,opts) * .then((response) => { * //網絡請求成功,執行該回調函數,獲得響應對象,經過response能夠獲取請求的數據 * //json text等 //你能夠在這個時候將Promise對象轉換成json對象:response.json() //轉換成json對象後return,給下一步的.then處理 * * return response.text(); * //或 return response.json(); * }) * .then((resonseData) => { * //處理請求獲得的數據 * }) * .catch((error) => { * //網絡請求失敗,執行該回到函數,獲得錯誤信息 * }) * * * * */ //練習一, 使用get 和post方式獲取數據 //將事件放在組件外部 function getRequest(url) { var opts = { method:"GET" } fetch(url,opts) .then((response) => { return response.text(); //返回一個帶有文本的對象 }) .then((responseText) => { alert(responseText) }) .catch((error) => { alert(error) }) } //Post方法, 須要請求體body /* * FromData * 主要用於序列化表單以及建立與表單格式相同的數據 * * var data = new FormData(); * data.append("name","hello"); * append方法接收兩個參數,鍵和值(key,value),分別表示表單字段的名字 和 字段的值,可添加多個 * * 在jQuery中,"key1=value1&key2=valu2" 做爲參數傳入對象框架,會自動分裝成FormData形式 * 在Fetch 中,進行post進行post請求,須要自動建立FormData對象傳給body * * */ function postRequest(url) { //將"key1=value1&key2=valu2" 形式封裝整FromData形式 let formData = new FormData(); formData.append("username","hello"); formData.append("password","1111aaaa"); var opts = { method:"POST", //請求方法 body:formData, //請求體 headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, } fetch(url,opts) .then((response) => { //你能夠在這個時候將Promise對象轉換成json對象:response.json() //轉換成json對象後return,給下一步的.then處理 return response.text }) .then((responseText) => { alert(responseText) }) .catch((error) => { alert(error) }) } var GetData = React.createClass({ render:function () { return( <View style={styls.container}> {/*注意: 方法調用方式,綁定了this */} <TouchableOpacity onPress={getRequest.bind(this,"http://project.lanou3g.com/projects/bj/reactnative/login.php?username=lanou&password=123")}> <View style={styles.btn}> <Text>Get</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={postRequest.bind(this,"http://project.lanou3g.com/projects/bj/reactnative/login.php")}> <View style={styles.btn}> <Text>Post</Text> </View> </TouchableOpacity> </View> ); } }); var styles = StyleSheet.create({ container:{ flex:1, backgroundColor:'cyan', marginTop:30, flexDirection:'row', justifyContent:'center', alignItems:'center' }, btn:{ width:60, height:30, borderWidth:1, borderColor:"yellow", justifyContent:'center', alignItems:'center' } });