选中复选框时提交表单 - 教程

Rob*_*b Y 9 ajax jquery

我正在尝试实现类似于37signals的ta-da列表的效果 - 我希望我的用户能够通过选中"完成"框来检查列表中的项目 - 换句话说,表单被提交到服务器在检查框.有没有人知道一个涵盖这样的东西的教程,或者可以指出我正确的方向?

谢谢Rob

SB2*_*B24 15

这很简单...

<input type="checkbox" onclick="this.form.submit();">
Run Code Online (Sandbox Code Playgroud)


Viv*_*ath 4

如果我正确理解你的问题:

您可以使用jQueryAJAX来完成此任务。在第一个示例中,我没有提交整个表单,而只提交了复选框的值:

jQuery("#myCheckbox").click(function() {
   var $checkbox = jQuery(this);
   var checkboxData = "checkboxvalue=" + $checkbox.val();

   jQuery.ajax({
      url: "http://some.url.here",
      type: "POST",
      data: checkboxData,
      cache: false,
      dataType: "json",
      success: function(data) {
          if(data["success"]) {
            //do some other stuff if you have to
            //this is based on the assumption that you're sending back
            //JSON data that has a success property defined
          }
      }
   });
});
Run Code Online (Sandbox Code Playgroud)

想必您会在服务器端有一些东西来处理该帖子。

如果您确实提交表单,您可以执行与上面相同的操作,只不过您需要序列化表单数据:

jQuery("#myCheckbox").click(function() {
   var formData = jQuery("#formID").serialize();

   jQuery.ajax({
      url: "http://some.url.here",
      type: "POST",
      data: formData,
      cache: false,
      dataType: "json",
      success: function(data) {
          if(data["success"]) {
            //do some other stuff if you have to
            //this is based on the assumption that you're sending back
            //JSON data that has a success property defined
          }
      }
   });
});
Run Code Online (Sandbox Code Playgroud)