Pass Dynamic Javascript Variable to Django/Python

后端 未结 1 1760
说谎
说谎 2021-02-04 16:21

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 c

相关标签:
1条回答
  • 2021-02-04 17:03

    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.

    With jQuery it would be as simple as

    Inside of your django template

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

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题