将动态 Javascript 变量传递给 Django/Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24152420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:16:23  来源:igfitidea点击:

Pass Dynamic Javascript Variable to Django/Python

javascriptjquerypythonajaxdjango

提问by Jason Hawkins

I have looked at a number of answers and other websites, but none answer my specific question. I have a webpage with "+" and "-" buttons, which should increment a variable called "pieFact". This variable must be updated dynamically without having to refresh the page. It should then be passed to my Django view each time the value is changed. This will be used to update the size of pie charts in a web map. I have the following:

我查看了许多答案和其他网站,但没有一个回答我的具体问题。我有一个带有“+”和“-”按钮的网页,它应该增加一个名为“pieFact”的变量。此变量必须动态更新,而不必刷新页面。每次更改值时,它都应该传递给我的 Django 视图。这将用于更新 web 地图中饼图的大小。我有以下几点:

<button type="button" id=bttnMinus onclick="pieFact=pieFact*0.9">-</button>
<button type="button" id=bttnPlus onclick="pieFact=pieFact*1.1">+</button></td> 
<script type="text.javascript">
    var pieFact=0;
</script>

How can I pass the value of "pieFact" to Django? Based on my limited knowledge, I think I may have to use AJAX post/get.

如何将“pieFact”的值传递给 Django?基于我有限的知识,我想我可能不得不使用 AJAX post/get。

回答by OozeMeister

In order to keep from refreshing the page, yes, you will need AJAX. I usually don't like to suggest libraries too much in answers, however, in the interest of being easily cross-browser compatible, I would suggest the use of jQuery.

为了避免刷新页面,是的,您将需要 AJAX。我通常不喜欢在答案中过多地建议库,但是,为了易于跨浏览器兼容,我建议使用jQuery

With jQuery it would be as simple as

使用 jQuery 就这么简单

Inside of your django template

在你的 Django 模板里面

<html>
    ...
    <head>
        <script>
            var URL = "{% url 'my_view_that_updates_pieFact' %}";
        </script>
    </head>
...

Later on...

稍后的...

You'll need to either POST or GET the data to the server via AJAX. To be more RESTful, whenever I need to send data to the server I use POST. jQuery provides the $.post()convenience function to AJAX data to a url via POST. The three parameters are the URL, the data to send (as a JavaScript object; think python dictionaries if you're not too familiar with JavaScript), and a callback function once the server sends back a response.

您需要通过 AJAX 将数据 POST 或 GET 发送到服务器。为了更加 RESTful,每当我需要向服务器发送数据时,我都会使用 POST。jQuery 提供了$.post()便利函数,可以通过 POST 将 AJAX 数据发送到 url。这三个参数是 URL、要发送的数据(作为 JavaScript 对象;如果您对 JavaScript 不太熟悉,请考虑使用 Python 字典)和服务器发回响应后的回调函数。

<script>
function updatePieFact(){
    var data = {'pieFact': pieFact};
    $.post(URL, data, function(response){
        if(response === 'success'){ alert('Yay!'); }
        else{ alert('Error! :('); }
    });
}

The .click()functions are basically the same thing as specifying onlickin the html attribute. Both click events update pieFactas you would expect and then call updatePieFact()to send the value of pieFactto the server.

这些.click()功能与onlick在 html 属性中指定的功能基本相同。两个点击事件pieFact都会按照您的预期更新,然后调用updatePieFact()将 的值发送pieFact到服务器。

$(document).ready(function(){
    $('#bttnMinus').click(function(){
        pieFact *= 0.9;
        updatePieFact();
    });
    $('#bttnPlus').click(function(){
        pieFact *= 1.1;
        updatePieFact();
    });
});
</script>

In views.py

在views.py中

Since I've used the $.post()function in the JavaScript, the request that Django is going to receive is going to have a method of "POST", so I check to make sure that the method is indeed POST(this means that if someone visits the URL for this view with something like a GET request, they won't update anything). Once I see that the request is, in fact, a POST, I check to see if the key 'pieFact'is in the dict request.POST.

由于我$.post()在 JavaScript 中使用了该函数,因此 Django 将要接收的请求将有一个 方法"POST",所以我检查以确保该方法确实是POST(这意味着如果有人访问此视图的 URL使用 GET 请求之类的内容,他们不会更新任何内容)。一旦我看到请求实际上是 a POST,我就会检查密钥'pieFact'是否在 dict 中request.POST

Remember when I set the variable datain the javascript to {'pieFact': pieFact}? That javascript just becomes the request.POST python dictionary. So, if in the javascript I had instead used var data = {'hello': pieFact};, then I would be checking if 'hello' in request.POSTinstead. Once I see that pieFactis in the request.POST dictionary, I can get its value and then do something with it. If everything is successful, I return an HttpResponsewith the string 'success'. This correlates with the check in javascript: if(response === 'success').

还记得我将datajavascript 中的变量设置为{'pieFact': pieFact}吗?该 javascript 只是成为 request.POST python 字典。因此,如果我在 javascript 中使用了var data = {'hello': pieFact};,那么我将if 'hello' in request.POST改为进行检查。一旦我pieFact在 request.POST 字典中看到它,我就可以获取它的值,然后用它做一些事情。如果一切都成功,我会返回HttpResponse带有字符串的'success'。这与 javascript: 中的检查相关if(response === 'success')

def my_view_that_updates_pieFact(request):
    if request.method == 'POST':
        if 'pieFact' in request.POST:
            pieFact = request.POST['pieFact']
            # doSomething with pieFact here...
            return HttpResponse('success') # if everything is OK
    # nothing went well
    return HttpRepsonse('FAIL!!!!!')

Hopefully that will get you pointed in the right direction.

希望这会让你指向正确的方向。