【问题标题】:Passing a Javascript variable to Django view将 Javascript 变量传递给 Django 视图
【发布时间】:2016-03-26 05:48:13
【问题描述】:

我使用它和 HTML CSS 制作了一个 JavaScript/jQuery 游戏。现在我正在尝试将所述游戏集成到 Django 后端。目前,我有一个 .js 文件,其中包含我所有的 Javascript/jQuery 逻辑。它是<linked>'ed 到 HTML 页面,基本上控制了游戏的整个流程。

如何在我的 Django 中访问我的 .js 文件中的 JavaScript 变量

.js 代码...
我希望在我的 Django 视图中可以访问 this.clicks 变量。

this.total = 18
this.clicks = 0
this.move = function(num){  //Adds or subtracts one from total depending on which player calls it
    if(this.total == 0){
        $('#oneone').show();
    }else if(this.total == 36){
        $('#twoform').show();
    }else{
        this.total += num
        this.clicks += 1
        return this.total
    }
}

Django 视图...

class EndGame(View):
    def get(self, request, victor, gameid, player1id, player2id):
        print(gameid)
        if int(victor) == 1:  ##player one
            self.TallyUpScore(1, player1id, player2id)
            self.UpdateGameStats(1, gameid)
        else:  ##player two
            self.TallyUpScore(2, player1id, player2id)
            self.UpdateGameStats(2, gameid)
        return redirect('/')

【问题讨论】:

  • 你的问题太笼统了,它本质上是要求一个关于如何使用 ajax 调用发布数据的教程

标签: javascript jquery python django


【解决方案1】:

您需要先检索 csrf 令牌:

    function getCookie(name) {
        var cookieValue = null;

        if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');

          for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);

            if (cookie.substring(0, name.length + 1) == (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
            }
          }
        }
        return cookieValue;
     }

然后使用 ajax 将您的数据发送到您的 django 视图:

$.ajax({
    headers: {
        'Content-Type':'application/json',
        'X-CSRFToken': getCookie('csrftoken')
    },
    url:  'here_your_view_url/' + this.clicks,
    type: "GET",
    success:function(response){
        //alert("success: " + response);
    },
    error:function (xhr, textStatus, thrownError){
        //alert("failure: " + xhr.statusText);
    }
}).done(function (response) {
    //alert("end");
});

views.py

    def my_view(request):
        clicks = request.GET.get('clicks')

urls.py

url(r'^here_your_view_url/(?P<clicks>\d+)', 'my_view')

我建议查看Django Ajax了解更多详情。

【讨论】:

  • 收到AttributeError: 'WSGIRequest' object has no attribute 'data' 错误有什么想法吗?
  • 我得到一个装满东西的疯狂的大物体
  • 我做到了,但它给了我这个错误...TypeError: post() takes 1 positional argument but 2 were given
  • 我正在使用基于类的视图
猜你喜欢
  • 2020-07-11
  • 1970-01-01
  • 2019-03-24
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
相关资源
最近更新 更多