2017-09-26 36 views
0

這是我的Django模板的一些內容。從模板中的標記腳本調用Django python函數

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

不,JavaScript的執行客戶端。您必須發送請求(例如AJAX)並在視圖中處理該請求以便在服務器上執行代碼。 – schwobaseggl

回答

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

+0

url行的確切內容是什麼?我無法理解 –

+0

您在urls.py文件中爲相應視圖(方法)定義的whaterver url。 ( url:「/ app /」,url:「/ accounts /」) – somil

相關問題