1.安裝模塊 npm install axios --save / npm install fetch-jsonp --save php
2.在使用的頁面引入react
import axios from 'axios'
import fetchJsonp from 'fetch-jsonp';
axios
import React from 'react' import axios from 'axios' class Axios extends React.Component{ constructor(props) { super(props) } getData=()=>{ var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20'; //接口後臺容許了跨域 alert(1) axios.get(api) .then((res)=>{ console.log(res) }).catch(()=>{}) } render() { return( <div> <button onClick={this.getData}>點擊獲取接口數據</button> </div> ) } } export default Axios
fetch-jsonpios
import React, { Component } from 'react'; import fetchJsonp from 'fetch-jsonp'; class FetchJsonp extends Component { constructor(props) { super(props); this.state = { list:[] }; } getData=()=>{ //獲取數據 var api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20"; fetchJsonp(api) .then(function(response) { return response.json() }).then((json)=> { // console.log(json); this.setState({ list:json.result }) }).catch(function(ex) { console.log('parsing failed', ex) }) } render() { return ( <div> <h2>FetchJsonp 獲取服務器jsonp接口的數據</h2> <button onClick={this.getData}>獲取服務器api接口數據</button> <hr /> <ul> { this.state.list.map((value,key)=>{ return <li key={key}>{value.title}</li> }) } </ul> </div> ); } } export default FetchJsonp;