您正在尝试访问在用户单击后端 Django 模板中的前端时创建的 javascript 变量。但是,您已经知道它不会起作用。
更好的选择是在 javascript 中重建 url:
$(document).on('click', '.alink', function () {
// Generate URL without "id" bit
var url = "{% url 'myapp:productdetail' %}";
var id = $(this).attr('id');
// Construct the full URL with "id"
document.location.href = url + "/" + id;
});
如果您没有可以返回所需 URL 的 django url 帮助程序,则可以打印出任何内容并简单地用 javascript 替换它,如下所示:
$(document).on('click', '.alink', function () {
var url = "{% url 'myapp:productdetail' 123 %}";
var id = $(this).attr('id');
// Construct the full URL with "id"
document.location.href = url.replace('123', id);
});