每次选中复选框时,我都会尝试将所有选中值的数组发送到 Controller ,但无法弄清楚如何使用 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);
}
Controller :
class BudgetController < ApplicationController
def view
....
end
end
如何将 selected_items 数组传递到 Controller 而无需重新加载页面?
最佳答案
这涉及将它们放入表单中并提交表单:
$('#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
});
});
然后您可以像在服务器端处理常规表单提交一样处理它们。
关于javascript - 当选中复选框时,如何动态地将复选框值从 View 传递到 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23409616/