2016-11-17 78 views
0

我很难提交此表:如何通过jquery ajax提交复选框?

<form action="/someurl" method="post"> 
    <input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5"> 
    <input type="checkbox" class="mychoice" name="name" value="apple"> Apple 
    <input type="checkbox" class="mychoice" name="name" value="orange"> Orange  
    <input type="checkbox" class="mychoice" name="name" value="pear"> Pear 
    </form> 

而jQuery的位:

$('.mychoice').click(function() { 
    $.ajax({ 
     url: '/someurl', 
     type: 'post', 
     dataType: 'json', 
     success: function(data) { 
       // ... do something with the data... 
       } 
    }); 
}); 

但是当我点击一个复选框,没有任何反应。我怎样才能解决这个问题?

更新:值得一提的是表单位于bootstrap模式。

+0

你什么时候运行jQuery代码? –

+0

它应该在引导模式下运行。 – Karlom

+0

当你的代码运行时,你确定你的元素在DOM中吗?你能发布一个片段的例子吗? –

回答

2

您错过了data属性。

例如:JQuery $.ajax() post - data in a java servlet

如果你想发送表单的内容,那么你会使用Form.serialize(),但你可以把你想要的任何数据放入属性中。

$(document).ready(function() { 
 
    $('.mychoice').click(function() { 
 
    var formData = $('#myForm').serialize(); 
 
    console.log('Posting the following: ', formData); 
 
    
 
    $.ajax({ 
 
     url: '/someurl', 
 
     data: formData, 
 
     type: 'post', 
 
     dataType: 'json', 
 
     success: function(data) { 
 
     // ... do something with the data... 
 
     } 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form action="/someurl" method="post" id="myForm"> 
 
    <input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5"> 
 
    <input type="checkbox" class="mychoice" name="name" value="apple">Apple 
 
    <input type="checkbox" class="mychoice" name="name" value="orange">Orange 
 
    <input type="checkbox" class="mychoice" name="name" value="pear">Pear 
 
</form>

+0

数据仅用于发送发布请求,否则任何数据都可以添加到url本身。 –

+0

'type:'post''是什么意思?这与你有什么不同吗? –

+2

我没有倒下你,所以保持你的裤子。即使你还没有解释如何序列化表单或填充数据,所以它仍然只有一半的答案。 –

0

试试这个:

$(document).ready(function(){ 
    $('.mychoice').change(function() { 
     $.ajax({ 
      url: '/someurl', 
      type: 'post', 
      dataType: 'json', 
      success: function(data) { 
       // ... do something with the data... 
      } 
     }); 
    }); 
}); 
+0

@Mister正面它不以什么方式回答问题。他问他能做什么;我说试试这个。这听起来像是对我的回答,但是再一次,我一生只会说英语。 –

0

供应缺失的数据

$(document).ready(function() { 
    $('.mychoice').click(function() { 
    $.ajax({ 
     url: '/someurl', 
     data: $(this).closest('form').serialize(), 
     type: 'post', 
     dataType: 'json', 
     success: function(data) { 
     // ... do something with the data... 
     } 
    }); 
    }); 
}); 
-1

尝试 '改变',而不是 '点击',像这样:

$('.mychoice').change(function(){...}) 
+0

我做了,但没有效果。我甚至在jquery函数中添加了一个'alert(“clicked”)',但是当我勾选一个复选框时它不会被触发。 – Karlom

+0

@Karlom在铬右键单击然后选择“检查元素”,你可能有JavaScript错误,导致JavaScript停止,或者,jquery没有正确包含 – evilReiko