我想每一个复选框被选中时发送的所有选定值的数组控制器,但无法弄清楚如何做到这一点使用AJAX。
I am trying to send an array of all checked values to the controller every time a checkbox is checked, but cannot figure out how to do this using AJAX.
html.erb:
<div class="items">
<input type="checkbox" class="item-checkbox" value="a">A
<input type="checkbox" class="item-checkbox" value="b">B
<input type="checkbox" class="item-checkbox" value="c">C
</div>
JavaScript的:
javascript:
var selected_items = [];
$(".item-checkbox").click(function() {
var item = $( this ).val();
selected_items.push(item);
}
控制器:
class BudgetController < ApplicationController
def view
....
end
end
我如何通过selected_items阵列控制器,而无需重新加载页面?
How do I pass the selected_items array to the controller without having to reload the page?
这将涉及把他们的表单中,并获得形式提交:
This would involve putting them within a form and getting the form to submit:
$('#MyForm').submit(function (event) {
event.preventDefault(); // stop form from submitting normally
var form = $(this); // get the form
var dataToSend = form.serialize(); // get the submitted form items
var url = form.attr('action'); // where we're submitting the data to
$.post(url, dataToSend, function (data) {
// optional function to deal with returned data
}).done(function (data) {
// what to do when it's completed
}).fail(function (jqXHR, textStatus, errorThrown) {
// what to do if it fails
});
});
您可以再处理它们像一个普通的表单提交服务器端。
You can then handle them like a regular form submission on the server side.