Django-如何将JavaScript变量保存到Django数据库中? [英] Django - How to save javascript variable into Django Database?

查看:65
本文介绍了Django-如何将JavaScript变量保存到Django数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"counter"的JavaScript变量,我想用它来更新在models.py中实例化的计数器变量.

I have a javascript variable called "counter", which I want to use to update a counter variable instantiated in models.py.

这是models.py的快照

Here is a snapshot of models.py

class Player(BasePlayer):
    #track the number of times the user has lost window focus
    blur_quantity = models.IntegerField(initial=0) 

以下是pages.html的示例

Here is an example of pages.html

{% block content %}
<button name="blur_button" value=counter onclick="Warn()" class="btn btn-primary btn-large">Blur Button</button>


{% endblock %}
{% block scripts %}
    <script>
        var counter  = 0;
       // Tracks window blurs
       $( document ).ready(function() {
          function onchange (evt) {
            counter++;
            console.log(counter);
          }

          window.onblur = onchange;

        });  

        function Warn() {
            alert(counter);
        }
</script>
{% endblock %}

现在,每当用户单击按钮时,"counter"的值应存储在某个位置.如何更新models.py(例如Django数据库)中的blur_quantity的值,以反映附加到blur_button的值?

Now, whenever the user clicks the button, the value of "counter" should be stored somewhere. How do I update the value of blur_quantity in models.py (e.g. my Django database) to reflect the value attached to the blur_button?

推荐答案

JavaScript:

JavaScript:

   var counter = 0;

  $( document ).ready(function() {
     function onchange (evt) {
       counter++;
       $.ajax({
         url: '/update_counter/',
         data: {'counter': counter},
         type: 'POST'
       }).done(function(response){
         console.log(response);
       });
     }

     window.onblur = onchange;

   }); 

views.py:

from django.http import HttpResponse
from models import Player

def update_counter(request):
    if request.method == 'POST':
        player = Player.objects.get()
        player.blur_quantity =  request.POST['counter']
        player.save()
        message = 'update successful'
    return HttpResponse(message)

urls.py:

from django.conf.urls import url

from views import update_counter

urlpatterns = [
   url(r'^update_counter/', update_counter)
]

基本上,JavaScript中调用中的 ajax 通过 POST 请求将 counter 发送到服务器. urls.py 将请求路由到您的 update_counter 方法,该方法将使用 counter 的值更新数据库.最后, update_counter 方法返回响应,该响应由JavaScript中的 done 函数处理.

Basically, the ajax in call in the JavaScript sends counter to the server via a POST request. urls.py routes the request to your update_counter method, which updates the database with the value of counter. Finally, the update_counter method returns a response, which is handled by the done function in the JavaScript.

这篇关于Django-如何将JavaScript变量保存到Django数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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