如何动态地通过从视图到控制器的复选框值,检查什么时候? [英] How do I dynamically pass a checkbox value from the view to the controller when it is checked?

查看:122
本文介绍了如何动态地通过从视图到控制器的复选框值,检查什么时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每一个复选框被选中时发送的所有选定值的数组控制器,但无法弄清楚如何做到这一点使用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.

这篇关于如何动态地通过从视图到控制器的复选框值,检查什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆