Call django urls inside javascript on click event

后端 未结 3 612
太阳男子
太阳男子 2020-12-31 21:49

I got a javascript onclick event inside a template, and i want to call one of my django urls with an id parameter from it, like this :

$(document).on(\'click         


        
3条回答
  •  無奈伤痛
    2020-12-31 22:13

    I think the best way to do this is to create a html data-* attribute with the URL rendered in a template and then use javascript to retrieve that.

    This way you avoid mixing js/django template stuff together. Also, I keep all of my JS in a separate file outside the view (which is a much better practice in general), and therefore trying to mix these two won't work.

    For instance, if you have a url you want, just create an html hidden element:

    
    

    Then, in your JS:

    $(document).on('click', '.alink', function () {
        var url = $("#Url").attr("data-url");
    });      
    

    I frequently use this pattern for dropdown lists so that I don't have to serve all of the options when I first render the page (and this usually speeds it up).

提交回复
热议问题