从模板中的标记脚本调用Django python函数

时间:2017-09-26 11:55:22

标签: python django templates

这是我的Django模板的一些内容。

...
<a id="ID" href="">Do operation with database.<a/>
...
<script type="text/javascript">
                    window.onload = function () {
                        var a = document.getElementById("ID");
                        a.onclick = function () {
                            if (confirm("do you really want to perform task?")) {
                                /** call python function in order to perform some operations with database **/
                            }
                            return;
                        }
</script>
...

该函数是例如(我们可以想象函数在views.py中):
    def performtask():
    #do my operation with the database

我的问题是,如何从我的模板中的脚本标记调用performtask()函数?

1 个答案:

答案 0 :(得分:1)

你应该使用ajax

   $.ajax({
        url: "http://abc,com/app/",
        type: "POST",
        data :{},
        success:function(result){
            //your code
        },
        error:function(error){
            //error handal
        }
    });

您可以在此处获取更多详细信息:

https://realpython.com/blog/python/django-and-ajax-form-submissions/

https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html