Call django urls inside javascript on click event

后端 未结 3 622
太阳男子
太阳男子 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:19

    You are trying to access javascript variable that is created at user click on frontend within your Django template at the backend. But, you already know that it would not work.

    A better option would be to reconstruct the url in javascript:

    $(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;
    });
    

    If you don't have a django url helper that would return a URL that you need, you can print out just any and simply replace it in javascript like so:

    $(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);
    });
    

提交回复
热议问题