Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

jquery - Call django urls inside javascript on click event

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 !!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...