【问题标题】:Ajax Django simple checkbox actionAjax Django 简单的复选框动作
【发布时间】:2014-09-12 23:17:02
【问题描述】:

我对表格的每一行都有一个复选框。我的目标是选中/取消选中复选框并更新我的 view.py 中的数据库。很抱歉这个简单的问题,但我从几天开始就在学习 Ajax,它仍然是一个未开发的世界。这是我的代码:

HTML
... 
<table>
      ...
      <tr><td>       
    <form action="mytemplate.html" method="GET" id="myform">{% csrf_token %}
        <input class="chktest" name="test" type="checkbox" value= "{{number}}">                                                                                                                                                                         
    </form>
      </td></tr>
      <tr><td>               
     <form action="mytemplate.html" method="GET" id="myform">{% csrf_token %}
        <input class="chktest" name="test" type="checkbox" value= "{{number}}">                                                                                                                                                                         
     </form>
     </td></tr>
     ...   
 </table>

**JQUERY**

<script type="text/javascript">
    $(document).ready(function() {           
        $('table tr td .chktest').click(function() {                           
                $.ajax({ 
                    data: $(this).serialize(), 
                    type: $(this).attr('method'), 
                    url: $(this).attr('action'), 
                    success: function(response) { 
                        // on success..
                    },
                    error: function(e, x, r) { 
                       // on error...                           
                    }
                }); 
            return false;

        }); 
    });
    </script>     

 **MYVIEW.PY**
 ...
 if request.is_ajax():        
    number = request.GET['number']        
    for obj in tab_company.objects.filter(id_number=number):
           obj.update(check=not obj.check)
    message = "Hello!"  
    return HttpResponse(json.dumps({'message': message}))   

这样,当我第一次单击复选框时,我会为每一行得到正确的数字。如果我在同一个复选框上再次选中它,它不会返回 False(取消选中)。我哪里错了?

【问题讨论】:

    标签: javascript jquery ajax django checkbox


    【解决方案1】:

    问题出在这一行

    tab_company.objects.filter(id_number=number).update(check=True)`
    

    您将值设置为 True,而不是切换它。您可以尝试以下方法吗:

    for obj in tab_company.objects.filter(id_number=number):
        obj.update(check=not obj.check)
    

    【讨论】:

    • 感谢@fluffels,但这并不能解决我无法设置为 False 的复选框的问题。这是正确的?我不会重新加载页面..
    • 问题是当你再次点击复选框时它并没有取消?
    • 也许是因为您覆盖了所有这些不同元素的点击事件?如果你只将 .chktest 放在 $ 选择器中会发生什么?
    猜你喜欢
    • 2018-03-20
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2017-09-29
    • 1970-01-01
    • 2011-08-24
    相关资源
    最近更新 更多