将动态Javascript变量传递给Django / Python [英] Pass Dynamic Javascript Variable to Django/Python

查看:282
本文介绍了将动态Javascript变量传递给Django / Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看了很多答案和其他网站,但是没有人回答我的具体问题。我有一个带有+和 - 按钮的网页,它应该增加一个名为pieFact的变量。此变量必须动态更新,无需刷新页面。每次更改值时,都应将其传递给我的Django视图。这将用于更新网络地图中饼图的大小。我有以下内容:

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:

<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>

如何将pieFact的值传递给Django?根据我有限的知识,我想我可能需要使用AJAX post / get。

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.

推荐答案

为了保持清醒页面,是的,你将需要AJAX。我通常不喜欢在答案中建议图书馆太多,但为了便于跨浏览器兼容,我建议使用 jQuery

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.

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



稍后...



您需要通过AJAX POST或将数据发送到服务器。要更加RESTful,每当我需要将数据发送到服务器时,我都使用POST。 jQuery通过POST将AJAX数据的 $ .post()便利功能提供给url。这三个参数是URL,要发送的数据(作为JavaScript对象;如果您不熟悉JavaScript,请考虑python字典),并且一旦服务器发回响应,就返回一个回调函数。

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.

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

.click()函数基本上与html属性中指定 onlick 相同,双击事件更新 pieFact ,您可以预期,然后调用 updatePieFact()发送值 pieFact

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

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



在views.py



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

In 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.

记住,当我将javascript中的变量数据设置为 {'pieFact': pieFact} ?那个javascript就成了request.POST的python字典。所以,如果在javascript中,我使用了 var data = {'hello':pieFact}; ,那么我会检查如果'hello'请求.POST 代替。一旦我看到 pieFact 在request.POST字典中,我可以得到它的值,然后用它做一些事情。如果一切都成功,我会返回一个 HttpResponse ,其中包含字符串'success'。这与javascript中的检查相关: if(response ==='success')

Remember when I set the variable data in 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.POST instead. Once I see that pieFact is in the request.POST dictionary, I can get its value and then do something with it. If everything is successful, I return an HttpResponse with the string 'success'. This correlates with the check in 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.

这篇关于将动态Javascript变量传递给Django / Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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