使用jQuery将模板变量传递给Django URL

3

在jquery中是否可以通过模板变量传递给django url?我已经尝试了将参数传递给django url的标准方法,但是出现了“No reverse match”错误。

Javascript代码:

<button id = "testid" href = "{%url 'test:justatest' id=8}">Click here for something</button>

<script type="text/javascript">
  var btn = $('#testid');

      btn.click(function (e) {
        var goto = $(this).attr('href');
          e.preventDefault();

    $.ajax({ 
    url: goto, 
    type: "GET",
    success: function(data){
        console.log(data);
        alert(data);
    }});
});

  </script>

urls.py

path('test/<int:id>',views.TestDetail.as_view(),name="justatest")

我也按照这篇文章尝试过,但只是得到了404错误。

<button id = "testid" href = "{%url 'test:justatest'%?id=8}">Click here for something</button>

<script type="text/javascript">
  var btn = $('#testid');

      btn.click(function (e) {
        var goto = $(this).attr('href');
          e.preventDefault();

    $.ajax({ 
    url: goto, 
    type: "GET",
    success: function(data){
        console.log(data);
        alert(data);
    }});
});

  </script>

我认为编写URL的正确方式应该是"{%url 'justatest' '8'}"。但是请考虑通过视图传递ID。 - dsax7
@filtfilt 实际上,当我们在项目中使用多个应用程序时,我们需要将应用程序的 URL 添加到主 URL 中,并在重定向时提及该应用程序的名称和 URL。 - Vinay Kumar
3个回答

0

模板渲染发生在页面发送到浏览器之前的服务器端。而JavaScript在页面呈现后在浏览器中执行。

根据Nids Barthwal的想法,您需要像她的答案一样的东西,但要注意replace函数将在呈现的URL上使用。

因此,在您的模板中,您可能会有类似以下内容:

let goto = "{% url 'justatest' 'temp_arg' %}";

最终呈现为:

let goto = "/test/temp_arg/";

现在你可以用想要的jQuery变量替换'temp_arg'。
let goto = goto.replace('temp_arg', $(this).attr('temp_id'))

0

运行成功!!

我尝试了下面的代码,它可以正常工作。

var url = "{% url 'my-ur-name' 1 %}".replace('1', $(this).attr('temp_id'));

0

我没有使用JS传递参数的经验。但是看了你的代码,我建议你尝试在语句末尾添加“%”:

“{% url ‘test:justatest’ id=8 %}”

告诉我进展如何!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接