每次选中复选框时,我都会尝试将所有选中值的数组发送到控制器,但无法弄清楚如何使用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:
var selected_items = [];
$(".item-checkbox").click(function() {
var item = $( this ).val();
selected_items.push(item);
}
控制器:
class BudgetController < ApplicationController
def view
....
end
end
如何在不重新加载页面的情况下将selected_items数组传递给控制器?
答案 0 :(得分:1)
这将涉及将它们放在表单中并使表单提交:
$('#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
});
});
然后,您可以像在服务器端提交常规表单一样处理它们。