Call django urls inside javascript on click event

你离开我真会死。 提交于 2019-12-12 08:14:36

问题


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', '.alink', function () {
        var id = $(this).attr('id');
        document.location.href ="{% url 'myapp:productdetailorder' id %}"
});

Course this is not working at all. Any idea ?

Thanks in advance !!


回答1:


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



回答2:


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:

<input type="hidden" id="Url" data-url="{% url 'myapp:productdetail' id %}" />

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




回答3:


The problem seems to be in that you using django template language in js static file(am i right?) Try to move that variable to html template file, ex:

<script type=text/javascript>
Var a = "{% url'myapp:productdetail' id %}" </script>

And in static js file:

document.location.href = a;


来源:https://stackoverflow.com/questions/37311042/call-django-urls-inside-javascript-on-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!