Reactjs之Axios、fetch-jsonp获取后台数据

1、新增知识点

/**
 Axios获取服务器数据(无法跨域,只能让后台跨域获取数据)
    react获取服务器APi接口的数据:
    react中没有提供专门的请求数据的模块。但是我们可以使用任何第三方请求数据模块实现请求数据
        axios介绍:          https://github.com/axios/axios       axios的作者觉得jsonp不太友好,推荐用CORS方式更为干净(后端运行跨域)
        1、安装axios模块npm install axios  --save   /  npm install axios  --save
        2、在哪里使用就在哪里引入import axios from ‘axios‘
        3、看文档使用
             var api=‘http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20‘;
             axios.get(api)
             .then(function (response) {
                            console.log(response);
                        })
             .catch(function (error) {
                            console.log(error);
                        });

 2、fetch-jsonp    https://github.com/camsong/fetch-jsonp
 fetch-jsonp请求:返回url会带回一个callback=
    1、安装 npm install fetch-jsonp  --save
    2、import fetchJsonp from ‘fetch-jsonp‘
    3、看文档使用
         fetchJsonp(‘/users.jsonp‘)
         .then(function(response) {
                      return response.json()
                    }).then(function(json) {
                      console.log(‘parsed json‘, json)
                    }).catch(function(ex) {
                      console.log(‘parsing failed‘, ex)
                    })
    4、其他请求数据的方法也可以...自己封装模块用原生js实现数据请求也可以...

 远程测试API接口:
    get请求:
        http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20
    jsonp请求地址:
        http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&callback=?
 */

2、案例实现

class Home12 extends React.Component{
    constructor(props){
        console.log("组件加载,首先加载构造方法---1")
        super(props);
        this.state={
            msg:"HOME12 组件信息",
            list:[],
            listjson:[]
        }
    }
    componentWillMount() {
        console.log("构造函数加载完成后,会加载componentWillMount(组件将要挂载)----2")
    }
    getData=()=>{
        //通过axios获取数据
        var api=‘http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20‘;
        alert("获取数据");
        axios.get(api).then((response)=> {
            console.log(response.data.result); //接口返回数据
            this.setState({
                //用到this,要用到this取向
                list:response.data.result
            })
        }).catch(function (error) {
            console.log(error);//捕获异常数据
        })
    }
    getfetchjsonpData=()=>{
        //通过fetchjsonp获取数据
        var api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
        fetchJsonp(api)
            .then(function(response) {
                return response.json()//返回的json数据
            }).then((json) =>{
            //console.log(‘parsed json‘, json)
            this.setState({
                listjson:json.result
            })
        }).catch(function(ex) {
            console.log(‘parsing failed‘, ex)
        })
    }
    render() {
        console.log("数据将要渲染---3")
        return(
            <div>
                <h2>HOME12组件首页</h2>
                <h1>axios获取数据</h1>
                <button onClick={this.getData}>获取服务器api接口数据</button>
                <hr/>
                <ul>
                    {
                        this.state.list.map( (value,key) =>{
                           return(<li key={key}>{value.title}</li>)
                        })
                    }
                </ul>
                <hr/>
                <h1>fetch-jsonp获取数据</h1>
                <button onClick={this.getfetchjsonpData}>获取服务器api接口数据</button>
                <hr/>
                <ul>
                    {
                        this.state.listjson.map( (value,key) =>{
                            return(<li key={key}>{value.title}</li>)
                        })
                    }
                </ul>
            </div>
        )
    }
    //生命的周期函数---组件加载完成
    componentDidMount() {
        console.log("组件加载完成---4")
        this.getData();
    }
}

原文地址:https://www.cnblogs.com/ywjfx/p/10430794.html

时间: 2024-07-29 13:35:30

Reactjs之Axios、fetch-jsonp获取后台数据的相关文章

Vue axios异步获取后台数据alert提示undefined

记录一个小问题,关于分页查询套餐 前台通过axios异步请求获取后台数据alert弹出数据提示undefined 下面有三个bean PageResult /** * 分页结果封装对象 */ public class PageResult implements Serializable { //总记录数 private Long total; //当前页结果 private List rows; //get,set方法省略 .... } QueryPageBean /** * 封装查询条件 */

Ajax 跨域请求 jsonp获取json数据

遇到Ajax的跨域请求出问题 找了中解决办法如下: 参考内容:http://justcoding.iteye.com/blog/1366102 由于受到浏览器的限制,该方法不允许跨域通信.如果尝试从不同的域请求数据,会出现安全错误.如果能控制数 据驻留的远程服务器并且每个请求都前往同一域,就可以避免这些安全错误.但是,如果仅停留在自己的服务器上,Web 应用程序还有什么用处呢?如果需要从多个第三方服务器收集数据时,又该怎么办? 理解同源策略 同源策略阻止从一个域上加载的脚本获取或操作另一个域上的

201507221403_《backbone之一——新建模型和集合、实例化模型、模型上监听事件的方法、模型设置和获取后台数据、配置理由方法、视图绑定事件的方法、绑定模型等》

一 . 新建 var model_1 = new Backbone.Model({'name':'hello'}); var model_2 = new Backbone.Model({'name':'hi'}); var models = new Backbone.Collection(); models.add( model_1 ); models.add( model_2 ); alert( JSON.stringify(models) ); 二. 实例化模型 var M = Backbo

前台通过ajax获取后台数据,PHP如何返回中文数据

现在经常使用Ajax调用后台php获取后台数据,但是PHP返回的数据如果含有中文的话,Ajax会无法识别,那咋整呢,我用的是比较笨的方法,但是实用: echo urldecode(json_encode(array('status'=>'1', 'errMsg'=>urlencode('数据传递错误,请重试')))); return;

用ajax获取后台数据,返回json数据,怎么在前台使用?

用ajax获取后台数据,返回json数据,怎么在前台使用呢? 后台 C# code ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 if (dataType == "SearchCustomer")                 {                     int ID;                     if (Int32.TryParse(CustomerID, out ID))                     {    

sencha touch 通过.axhx获取后台数据时,Unable to parse the JSON returned by the server: Error: You&#39;re trying to

注意:如果你的store跟我一样是使用.ashx从.NET后台获取的,并且用sencha cmd自带的web服务器调试,在chrome调试的时候回会返回如下错误. [WARN][Ext.data.reader.Reader#process] Unable to parse the JSON returned by the server: Error: You're trying to decode an invalid JSON String: <%@ WebHandler Language=&qu

JavaScript中fetch获取后台数据

除了XMLHttpRequest对象来获取后台的数据之外,还可以使用一种更优的解决方案——fetch ㈠fetch示例 fetch获取后端数据的例子: // 通过fetch获取百度的错误提示页面 fetch('https://www.baidu.com/search/error.html') // 返回一个Promise对象 .then((res)=>{ return res.text() // res.text()是一个Promise对象 }) .then((res)=>{ console.

获取后台数据分页

html创建一个存放内容的容器,以及分页的容器: <div id="content"></div> <div id="pager"></div> js如下: $.ajax({ url: "url",//headers: {//"AccessToken" : "token"//},  //如果需要 type: "GET/POST", data

mvc 页面简单get获取后台数据

后台方法 public ActionResult Linq() { var lt = UserSys.FindAll(); Hashtable ht = new Hashtable(); ht.Add("data",lt); return Json(ht, JsonRequestBehavior.AllowGet); } 页面元素 <input type="text" name="ID" /> <input type="