简体   繁体   中英

passing JavaScript variable to Django

How can I pass a js variable to Django?

I have this simple code:

$(".update_btn").click(function() {
 var row_id=$(this).attr("row_id")

I want to pass row_id as index to a Django parameter called ticket_row , so that I could have ticket_row[row_id][1] I started to pass the first index with

console.log("{{ ticket_row['" + row_id + "'] }}") 

but it's working correctly. So, I need some help here :)

Any one has any suggestion / solution?

Thanks!

You may want to use AJAX to send a request to the server. Or you could redirect the user to the page with an additional GET parameter: /path/to/page.html?row_id=2 , replacing 2 with the ID you receive in JavaScript. Then access it via the request in your view:

def index(request):
    . . .
    row_id = 0
    if "row_id" in request.GET:
        row_id = int(request.GET["row_id"])
    try:
        selected_row = ticket_row[row_id]
    except IndexError:
        selected_row = ticket_row[0]
    return render(request, self.template_name, {"selected_row": selected_row})

In your template, you would then use:

console.log("{{ selected_row }}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM