【问题标题】:Javascript function excute automatically in web2pyJavascript函数在web2py中自动执行
【发布时间】:2016-03-28 04:06:52
【问题描述】:

我在前端有一个复选框,想根据复选框的状态更新数据库,我也有保存按钮来提交。

现在我很困惑。每次我转到 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>

【问题讨论】:

    标签: javascript python html web2py


    【解决方案1】:

    您似乎希望在页面加载后由浏览器执行 Python 函数。这不是 web2py 模板的工作方式。模板包含 Python 代码,在页面发送到浏览器之前在服务器上执行。因此,对change() 函数的调用发生在页面到达浏览器之前。

    您可能想要做的是在浏览器中触发 Ajax 调用,这将调用服务器上的单独函数来处理更新。您可以通过 jQuery(或其他合适的 Javascript 选项)来处理它,或者使用 web2py 的内置 Javascript ajax() 函数,如 here 所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多