最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Django, update part of the page - Stack Overflow

programmeradmin15浏览0评论

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.

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.

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.

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.

Share Improve this question edited Jan 15, 2014 at 9:20 Sudipta 4,9712 gold badges30 silver badges42 bronze badges asked Jan 15, 2014 at 9:09 KiarashKiarash 8,02810 gold badges46 silver badges72 bronze badges 3
  • 1 Sounds like basic ajax to me. You fetch the results and update the output box using javascript. – keyser Commented Jan 15, 2014 at 9:10
  • 1 I know it should be basic. can you point me to some doc or snippet somewhere? – Kiarash Commented Jan 15, 2014 at 9:16
  • I was looking for an answer to this title and I found another solution based on htmx, may this is ment be useful for other ones: htmx – Omid Estaji Commented Sep 4, 2022 at 15:26
Add a ment  | 

2 Answers 2

Reset to default 8

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 es here
    return render(request, 'submit.html', {})

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

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

in submit.html add

<head>
    <script src="http://code.jquery./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>

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 );)

see Stop setInterval call in JavaScript

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

Here I have uploaded working version

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

Some reading

Auto-refreshing div with jQuery - setTimeout or another method?

This could be what you are looking for:

var ajaxForm = function() {
  $.ajax({
    type: 'POST',
    contentType: 'application/json',
    dataType: 'json',
    url: '/path/to/django/controller',
    // The data sent to the Django view in JSON format
    data: JSON.stringify({
      formField: $('#body').val()
    }),
    success: function (data) {
      $('#output-box').html(data);
    }
  });
}

$('#form').on('submit', function (e) {
  e.preventDefault();
  ajaxForm();
});

The implementation of a Django controller can be something like:

import json
from django.http import HttpResponse

def ajax_view(request):
    if request.method == 'POST':
        request_data = json.load(request.raw_post_data)
        # do something
        response_data = {}
        response_data['result'] = 'Failed'
        response_data['message'] = 'Your test not ended well'
        return HttpResponse(
            json.dumps(response_data),
            content_type='application/json'
        )
发布评论

评论列表(0)

  1. 暂无评论