2016-03-28 62 views
0

我在前端有一個複選框,並且想根據複選框的狀態更新數據庫,我也有保存按鈕來提交。在web2py中自動執行Javascript函數

現在我感到困惑。每次我轉向changeActive/id頁面,無需點擊按鈕,它就會直接更新數據庫。

警報正常工作。

這是控制器代碼:

def changeActive(): 
    post=db.student(request.args(0,cast=int)) 
    def change(value): 
     changeStatus=db(db.student.id==post.id).update(is_active=value) 
     return changeStatus 
    return locals() 

這是changeActive.html

{{extend 'layout.html'}} 
<h1>it is a test</h1> 
<h2>{{=post.name}}</h2> 
<h2>{{=post.id}}</h2> 
<h2>{{=post.is_active}}</h2> 


<input type=checkbox id=is_active> 
<input id="save" type="button" value="save"/> 
<script type="text/javascript"> 
window.onload=function() 
    { 
     var saveButton=document.getElementById('save'); 
     saveButton.onclick=function() 
     { 
      var changeSt=document.getElementById('is_active'); 
      if (changeSt.checked) 
      { 
       alert('active') 
       {{change('T')}} 
      } 
      else 
      { 
       alert ('not active') 
       {{change('F')}} 
      } 
     }; 
    }; 
</script> 

回答

0

看樣子你期待的Python功能頁面有後,由瀏覽器執行的代碼已加載。這不是web2py模板的工作方式。模板包括Python代碼,在頁面發送到瀏覽器之前,在服務器上執行。因此,在頁面到達瀏覽器之前,纔會調用change()函數。

你可能想要做的是在瀏覽器中觸發一個Ajax調用,該調用將在服務器上調用一個單獨的函數來處理更新。您可以通過jQuery(或其他合適的Javascript選項)處理,或使用web2py的內置Javascript ajax()函數,如here所述。