在点击事件中调用javascript里面的django网址 [英] Call django urls inside javascript on click event

查看:66
本文介绍了在点击事件中调用javascript里面的django网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模板中有一个javascript onclick事件,我想从它调用一个带有id参数的django url,如下所示:

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 ?

提前致谢!!

推荐答案

你是试图访问在用户点击后端Django模板中的前端创建的javascript变量。但是,你已经知道它不会起作用。

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.

更好的选择是在javascript中重建网址:

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

如果你没有可以返回你需要的URL的django url帮助器,你可以打印出来的任何内容,只需将其替换为javascript,如下所示:

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

这篇关于在点击事件中调用javascript里面的django网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆