Django-如何将模板中的变量作为POST请求返回到视图

时间:2018-12-21 17:32:26

标签: javascript html django django-templates django-views

我想作为POST请求将模板中的变量返回到视图。该变量是动态的,由jquery脚本定义。我对javascript不太了解,所以我不知道如何获取可变的分钟和秒,因此我可以将它们作为POST请求显示在下一个站点。

这是我想要在其中获取变量的分钟和秒模板:

{% extends "base_generic2.html" %}


{% block content %}

    <!-- Timer function -->
    <script type="text/javascript">
        var sec = 0;
        function pad ( val ) { return val > 9 ? val : "0" + val; }
        setInterval( function(){
            $("#seconds").html(pad(++sec%60));
            $("#minutes").html(pad(parseInt(sec/60,10)));
        }, 1000);
    </script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <span id="minutes"></span>:<span id="seconds"></span>

  <form action="results" id=results method="POST">

    <!-- after clicking on this button the minutes and seconds should also be sent as a POST request -->

    <div class="command">
      <button type="submit" name="ctest_submit">Submit solution</button>
    </div>

  </form>


{% endblock %}

这是我要使用分钟和秒的视图:

def viewtest(request):
    if request.method == 'POST':
        minutes = request.POST['minutes']
        seconds = request.POST['seconds']
        return render(request, 'results.html', {'minutes': minutes, 'seconds': seconds})

    else:

    #this section should not be important I think

如何查看分钟和秒钟?

1 个答案:

答案 0 :(得分:0)

发表ajax帖子...

$.ajax({
  type: "POST",
  url: "/theurl/to/your/view",
  data: {'minutes':yourMinuteVariable, 'seconds':yourSecondsVAriable},
  success: success,
  dataType: dataType
});