zoukankan      html  css  js  c++  java
  • vue使用axios获取后端数据并展示

    1.后端python django代码:

    import json
    from django.shortcuts import HttpResponse
    from django.http import JsonResponse
    from databases_models import models
    from django.core import serializers
    
    def serverhost_list(request):
        host_list = models.GameServerVersion.objects.all()
        host_list_json = serializers.serialize("json",host_list)    #获取到的数据类型为字符串(str)
        host_list_json = json.loads(host_list_json) #将字符串数据转成json类型
        print(type(host_list_json))
        result = {
            "status": 0,
            "message": host_list_json
        }
        return HttpResponse(json.dumps(result,ensure_ascii=False),content_type='application/json')

    2.前端html vue代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Index</title>
        <script src="static/js/vue.js"></script>
        <script src="static/js/axios.min.js"></script>
    </head>
    <body>
    <div id="get_host_data">
        <button @click="GetHostData">获取数据</button>
        <table class="table table-bordered table-hover table-striped">
            <thead>
            <tr>
                <td>ID</td>
                <td>版本包</td>
                <td>md5</td>
            </tr>
            </thead>
            <tbody>
                <tr v-for="(item, index) of host_list" :key="item.pk">
                    <td>{{ item.pk }}</td>
                    <td>{{ item.fields.package_version }}</td>
                    <td>{{ item.fields.md5_number }}</td>
                </tr>
            </tbody>
        </table>
    </div>
    <script>
        new Vue({
            el:"#get_host_data",
            data: {
                host_list: []
            },
            methods:{
                GetHostData:function(){
                    var url = "http://127.0.0.1:8001/super_cmdb/serverhost_list/";
                    axios.get(url).then(response => {
                        if (response.data.status==0) {
                            this.host_list = response.data.message;
                            console.log(response.data.message);
                            console.log("获取机器列表成功")
                    } else {
                            console.error("获取机器列表失败")
                        }
                    })
                }
            },
            mounted:function () {   //自动触发写入的函数
                this.GetHostData();
            }
        })
    </script>
    </body>
    </html>

    根据后端返回的数据字段取信息

  • 相关阅读:
    三元表达式、递归、匿名函数
    迭代器、生成器、面向对象
    LeetCode35-搜索插入位置(二分查找)
    自动化测试框架搭建3-TestNG
    LeetCode28-实现strStr()(水题)
    前端页面与Nodejs使用websocket通信
    LeetCode14-最长公共前缀(水题)
    LeetCode13-罗马数字转整数(水题)
    AngularJS学习3-服务(service)/http服务/跨域
    九度OJ 1001:A+B for Matrices
  • 原文地址:https://www.cnblogs.com/chenjw-note/p/13735348.html
Copyright © 2011-2022 走看看