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>

 

根據后端返回的數據字段取信息

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM