Refresh div using JQuery in Django while using the template system

前端 未结 2 1918
旧时难觅i
旧时难觅i 2020-12-14 05:22

I want to refresh a div tag in Django that contains temperature data. The data is fetched every 20 seconds. So far I have achieved this using these functions:



        
相关标签:
2条回答
  • 2020-12-14 05:43

    NOTE: If 'testing.html' has more content than the one on the question, the .js will be:

    function refresh() {
    $.ajax({
      url: '{% url monitor-test %}',
      success: function(data) {
      var dtr = $("#div_to_refresh", data);
      $('#div_to_refresh').html(dtr);
            }
        });
      setTimeout("refresh()", 3000);
    }
    
    $(function(){
        refresh();
    });
    
    0 讨论(0)
  • 2020-12-14 05:46

    The way I normally get around the 3-4 "concurrent" requests for such situations is to put the setTimeout() call inside the function I want to run repeatedly.

    function refresh() {
        $.ajax({
            url: '{% url monitor-test %}',
            success: function(data) {
                $('#test').html(data);
            }
        });
        setTimeout(refresh, 10000);
    }
    
    $(function(){
        refresh();
    });
    

    That makes it so every time the refresh function is called, it will automatically set itself to be called again in 10 seconds. Another idea (if you still have problems) is to move the setTimeout into the success function in the AJAX call:

    function refresh() {
        $.ajax({
            url: '{% url monitor-test %}',
            success: function(data) {
                $('#test').html(data);
            }
            setTimeout(refresh, 10000);
        });
    }
    
    $(function(){
        refresh();
    });
    

    That option might be a little bit sketchy if, for whatever reason, the AJAX call does not succeed. But you can always get around that with other handlers, I suppose...

    One suggestion I have (not particularly related to your question) is putting the whole <table> thing in the template that you render and return your temperature view. So, in your main template:

    <div id="test">
    {% include 'testing.html' %}
    </div>
    

    and in testing.html:

    <table><tr>
    {% for label, value in temperature.items %}
        <td>{{ label }}</td>
        <td>{{ value }}</td>
    {% endfor %}
    </tr></table>
    

    Something about inserting part of a table the way you currently have it makes me want to cry :) Sending a few more bytes over the wire in AJAX calls shouldn't hurt anything.

    0 讨论(0)
提交回复
热议问题