django点击前端按钮展示后台列表

 

需求:通过点击前端的一个按钮,展示后台view中的数据

views.py

def index(request):
    #if request.method == 'POST':
    p = subprocess.Popen("ls -l", shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    lines = []
    while True:
        line = p.stdout.readline()
        if line:
            print(line)
            lines.append(line)
        else:
            break
    return JsonResponse(lines, safe=False)


def list(request):
    return render(request, 'websocket/list.html')

 

urls.py

from django.conf.urls import url
from . import views
from django.urls import path


urlpatterns = [
    url(r'^index/$', views.index),
    url(r'^list/$', views.list),
]

 

 

list.html

<!DOCTYPE html >
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>测试demo</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<div class="form-css">
    <button id="action">查看证书</button>
    <div id="content"></div>
</div>
</body>

<script>
    $("#action").click(function(){
        $.ajax({
            url: '/websocket/index',
            type:"GET",
            success:function(data){
                console.log(data)
                $.each(data, function(k, v){
                    $("#content").append(v+'<br/>')
                });
            }
        })
    })
    // 方法2:$('#action').click(function(){
    //       $.getJSON('/websocket/index',function(ret){
    //         //返回值 ret 在这里是一个列表
    //         for (var i = ret.length - 1; i >= 0; i--) {
    //           // 把 ret 的每一项显示在网页上
    //           $('#content').append(ret[i]+'<br/>')
    //         };
    //       })
    //   })

</script>


<style>
.form-css{
    margin-top: 20px;
    padding: 0 20px;
}
</style>

</html>

 

posted @ 2021-06-15 14:35  坚强的小蚂蚁  阅读(529)  评论(0编辑  收藏  举报