有个功能:web上需要定时刷新后台数据
解决方案:数据通过json传给js,设置定时器进行页面局部刷新处理
代码:
#django后台代码 @csrf_exempt @login_required def deploy_json(request, id): with open("/data/shell/autodeploy.log", "r") as data: lines = len(list(enumerate(data))) if int(id)<=lines: print lines jsondata = json.dumps([{"subject" : linecache.getline("/data/shell/autodeploy.log",int(id)), "count" : lines}], ensure_ascii=False) print jsondata response = HttpResponse() response[‘Content-Type‘] = "text/javascript" response.write(jsondata) return response data.close() else: return HttpResponse() data.close() @csrf_exempt @login_required def auto_deploy(request): if request.method == ‘POST‘: subcmd.Jso_out("sh /data/shell/autodeploy.sh | tee /data/shell/autodeploy.log") return render_to_response("deploy/auto_deploy.html") elif request.method == ‘GET‘: return render_to_response("deploy/auto_deploy.html")
#html代码 {% extends "default/base.html" %} {% block title %} 发布系统 {% endblock %} {% block content %} <body class="pageBg"> <h3 class="w_1320 pageTitle"> <span>发布系统</span>预发布环境一键发布 </h3> </body> <form method="POST" action="/deploy/pre_auto"> {% csrf_token %} <p align="left" class="style5"> <input type="submit" class="pageTitle_input01" value="发布(预发布)"> </form> <pre class="pre-scrollable prettyprint linenums Lang-bash"> 输出信息: <script type="text/javascript" language="javascript"> var i = 0; function update(id) { $.getJSON("/deploy/" + id + "/",function(data) { $("#content").append(‘<p>‘ + data[0].subject + ‘</p>‘); console.log(id,Number(data[0].count)); if(id >= Number(data[0].count)){ clearInterval(time); } }); } var time = setInterval(function() { i += 1; update(i) }, 1000); $(document).ready(function() { {# timeDown(3, 0) #} update(0) }) </script> <p id="time"></p> <div id="content"></div> </pre> {% endblock %}
效果:
时间: 2024-10-05 05:43:44