原生的ajax+vue请求数据渲染数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原生的ajax+vue请求数据渲染数据相关的知识,希望对你有一定的参考价值。

参考技术A // 定义工具方法

let Util =

    /**

    * 发送异步请求

    * @url 请求的地址

    * @fn 请求成功时候的回调函数

    **/

    getData(url, fn)

        // 实例化xhr对象

        let xhr = new XMLHttpRequest();

        // 监听状态变化

        xhr.onreadystatechange = () =>

            // 监听数据请求完毕

            if (xhr.readyState === 4)

                // 判断状态码

                if (xhr.status === 200)

                    // 将数据转化成json字符串

                    fn && fn(JSON.parse(xhr.responseText))

               

           

       

        // 打开请求

        xhr.open('GET', url, true);

        // 发送数据

        xhr.send(null)

    ,

    postData(url, params, fn)

        // 实例化xhr对象

        let xhr = new XMLHttpRequest();

        // 监听状态变化

        xhr.onreadystatechange = () =>

            // 监听数据请求完毕

            if (xhr.readyState === 4)

                // 判断状态码

                if (xhr.status === 200)

                    // 将数据转化成json字符串

                    fn && fn(JSON.parse(xhr.responseText))

               

           

       

        // 打开请求

        xhr.open('POST', url, true);

        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=utf-8");

        // 发送数据

        xhr.send(params);

    ,

    /**

    * 将对象转化成query的形式

    * @obj 转化的对象 color:red, num:100

    * return ?color=red&num=100

    **/

    objToQuery(obj,type)

        type = type ? '':'?';

        let result = '';

        // 遍历对象,转化成json

        for (var i in obj)

            result += '&' + i + '=' + obj[i]

       

        // 去除最后一个&

        return type + result.slice(1)

   



new Vue(

  el:"#app",

  data:

    msg:"hello world",

    list:[]

  ,

  created:function()

    var that = this;

    // 提供post,get请求

    Util.getData("https://a.daxiangclass.com/offer.php/api/v1/interview?page=1&size=100",function(res)

        that.list = res.data;     

    );

 

)

item.title

<p>item.title</p>//渲染数据

以上是关于原生的ajax+vue请求数据渲染数据的主要内容,如果未能解决你的问题,请参考以下文章

Vue解决vue-resources异步请求问题

使用axios获取数据并渲染到HTML页面

vue实战使用ajax请求后台数据(小白)

vue中的ajax请求

vue.js 渲染包含 vue.js 语法的 ajax 数据

原生Ajax