Pass Dynamic Javascript Variable to Django/Python

后端 未结 1 1761
说谎
说谎 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

    
        ...
        
            
        
    ...
    

    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.

    
    

    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)
提交回复
热议问题