【问题标题】:Pass a template variable to django url using jquery使用 jquery 将模板变量传递给 django url
【发布时间】:2019-04-07 22:25:34
【问题描述】:

是否可以使用 jquery 将模板变量传递给 django url?我尝试了将参数传递给 django url 的标准方法,但我没有得到反向匹配。

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")

我也尝试过这个 this post 但我只收到 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。
  • @filtfilt 实际上,当我们在项目中使用多个应用程序时,我们需要在主 url 中添加应用程序 url,并且在重定向时我们需要在 url 中提及 Appname

标签: jquery django


【解决方案1】:

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

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

告诉我这是怎么回事!

【讨论】:

    【解决方案2】:

    工作!!

    我尝试了下面的代码及其工作。

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

    【讨论】:

      【解决方案3】:

      在页面被发送到浏览器之前,模板呈现发生在服务器中。页面渲染完成后,JavaScript 会在浏览器中执行。

      根据 Nids Barthwal 的想法,您需要类似她的答案,但要注意替换功能将用于呈现的 URL。

      所以在你的模板中,你可能有这样的东西:

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

      最终呈现为:

      let goto = "/test/temp_arg/";
      

      现在您可以将“temp_arg”替换为您想要的 jquery 变量。

      let goto = goto.replace('temp_arg', $(this).attr('temp_id'))
      

      【讨论】:

        猜你喜欢
        • 2019-04-03
        • 2011-03-04
        • 2014-11-30
        • 2015-05-14
        • 1970-01-01
        • 2015-12-31
        • 2018-12-03
        • 2020-10-23
        • 1970-01-01
        相关资源
        最近更新 更多