如何将Django模板上下文变量传递给JS函数

时间:2022-04-21 06:52:56

I am trying to create a simple web link toggle for following or unfollowing a question in my app. I got close using the info My Own Like Button: Django + Ajax -- How? but am not quite there.

我正在尝试创建一个简单的web链接,用于在我的应用程序中进行跟踪或取消问题。我使用自己喜欢的按钮——Django + Ajax——关闭了它。但我不太明白。

My problem is that I cannot dynamically pass question.id to my JS function as the answer in the above link implies. Ie

我的问题是我不能动态地传递问题。id到我的JS函数,正如上面链接中的答案所示。即

The hard-wired JS code below DOES work. It passes '12' as a valid param for the view tied to /question/follow-unfollow-inline/. But when I try to replace '12' with a context variable '{{ question.id }}' from the template that calls this JS code, my function passes the string '{{ question.id }}' back to /question/follow-unfollow-inline/ rather than it's value. How do I fix this?

下面的硬编码的JS代码是有效的。它将'12'作为绑定到/question/follow-unfollow-inline/的视图的有效参数。但是当我试图用上下文变量“{问题”替换“12”时。id}'从调用这个JS代码的模板中,我的函数传递字符串“{问题”。id}'返回到/question/follow-unfollow-inline/而不是它的值。我怎么修复这个?

$(function () {
    $("#follow_unfollow_toggle").click(function () {
        $.ajax({
            type: "POST",
            url: "/question/follow-unfollow-inline/",
            data: { 'qid': '12' },
            success: function (e) {
                alert('Success!');
            }
        });
    });
});

For now, I'm using @csrf_exempt on my view, but I know I should pass it as data.

现在,我在视图中使用@ csrf_豁免权,但是我知道我应该将它作为数据传递。

1 个解决方案

#1


2  

You could define it on your anchor tag with data- attribute:

您可以使用data- attribute在锚标记上定义它:

Template:

模板:

<a id="follow_unfollow_toggle" href="#" data-qid="{{ question.id }}">Like</a>

Js file:

Js文件:

$(function () {
    $("#follow_unfollow_toggle").click(function () {
        $.ajax({
            type: "POST",
            url: "/question/follow-unfollow-inline/",
            data: { 'qid': $(this).data('qid') },
            success: function (e) {
                alert('Success!');
            }
        });
    });
});

#1


2  

You could define it on your anchor tag with data- attribute:

您可以使用data- attribute在锚标记上定义它:

Template:

模板:

<a id="follow_unfollow_toggle" href="#" data-qid="{{ question.id }}">Like</a>

Js file:

Js文件:

$(function () {
    $("#follow_unfollow_toggle").click(function () {
        $.ajax({
            type: "POST",
            url: "/question/follow-unfollow-inline/",
            data: { 'qid': $(this).data('qid') },
            success: function (e) {
                alert('Success!');
            }
        });
    });
});