Django,更新页面的一部分 [英] Django, update part of the page

查看:276
本文介绍了Django,更新页面的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个简单的代码测试服务器。客户将在网页上提交其代码,我们将使用两个测试用例(可能需要几分钟)来运行它,然后我们将结果发布。该页面将很简单,其中包含提交表单和输出框。

I'm trying to implement a simple code testing server. The client will submit their code on the webpage and we will run it with two test cases (which could take several minutes) and we'll post the results. The page will be simple with a submission form and an output box.

我的问题是更新输出框。我正在寻找实现输出框的最简单方法,以便在运行不同的测试用例时显示结果。

My problem is with updating the output box. I'm looking for the simplest way to implement the output box so that we show results as we run different test cases.

我尝试了Google搜索对于解决方案,我发现了一些类似socket.io的东西,但是我对ajax和socket.io甚至js的经验都非常有限,因此我正在寻找最简单的方法来实现。

I tried googling for solutions and I found some like socket.io but my experience with ajax and socket.io or even js is very limited so I'm looking for the simplest way to do this.

推荐答案

如果您正在寻找代码来自动更新HTML中的字段,则可以使用下面的代码。 JavaScript中的setInterval计划每隔1秒钟将get_log视图拉出一次,以获取get_log_from_disk方法的结果。

In case you are looking for code to auto-update a field in HTML here is the code which you could use. The setInterval in JavaScript schedules get_log view to be pulled every 1 second for result of get_log_from_disk method.

urls.py

    url(r'^get_log/$', 'myapp.views.get_log', name='get_log'),
    url(r'^submit/$', 'myapp.views.submit', name='submit'),

views.py

def submit(request):
    ## Handle POST
    ## Your code comes here
    return render(request, 'submit.html', {})

def get_log_from_disk():
    ## Your code comes here
    return "Test 1 OK; Test 2 OK"

def get_log(request):
    results = get_log_from_disk()
    return HttpResponse(results)

在commit.html中添加

in submit.html add

<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>

<body>
[<div id="output_box"></div>]

<script>
$(document).ready(function() {
  $.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
  var my_refresh = setInterval(function() {
    $('#output_box').load('/get_log/');
  }, 1000); // the "1000"
});

</script>
</body>

您可以修改 $('#output_box')。load('/ get_log /'); 测试请求的状态,当返回 204 No Content时,您可以删除该函数(clearInterval(my_refresh);)

You could modify "$('#output_box').load('/get_log/');" to test for status of request and when "204 No Content" is returned you can remove the function (clearInterval(my_refresh );)

请参见在JavaScript中停止setInterval调用

修改get_log视图以返回当没有更多内容要发送时,显示为 204 No Content。

Modify get_log view to return "204 No Content" when there is no more content to be sent.

此处我已上传工作版本

https://github.com/lukaszszajkowski/ Django-jQuery-Example-update-part-of-page / tree / master

一些阅读

使用jQuery自动刷新div-setTimeout还是其他方法?

这篇关于Django,更新页面的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆