简体   繁体   English

将JavaScript变量传递给Django

[英]passing JavaScript variable to Django

How can I pass a js variable to Django? 如何将js变量传递给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 我想将row_id作为索引传递给一个名为ticket_row的Django参数,以便可以有ticket_row[row_id][1]我开始传递第一个索引为

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. 您可能要使用AJAX将请求发送到服务器。 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. 或者,您可以使用其他GET参数将用户重定向到页面: /path/to/page.html?row_id=2 2 ,将2替换为您在JavaScript中收到的ID。 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 }}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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