Javascript 如何解析表单数据以在jQuery中使用JSON?

Javascript 如何解析表单数据以在jQuery中使用JSON?,javascript,jquery,json,forms,Javascript,Jquery,Json,Forms,我试图获取选中的复选框的值,并将它们存储在数组中,然后通过json函数发送给控制器。未显示警报(“我已完成拆分”)。请帮助我。split适用于字符串。您可以在每个数组索引上使用split而不是在整个数组上使用 如果确实要分割数组checkedValues,则循环遍历此数组,然后对每个索引使用分割 像这样: var checkedValues = $('.required:checked').map(function () { return this.value;

我试图获取选中的复选框的值,并将它们存储在数组中,然后通过json函数发送给控制器。未显示警报(“我已完成拆分”)。请帮助我。

split
适用于字符串。您可以在每个数组索引上使用
split
而不是在整个数组上使用

如果确实要分割数组
checkedValues
,则循环遍历此数组,然后
对每个索引使用分割

像这样:

 var checkedValues = $('.required:checked').map(function () {
                return this.value;
            }).get();

            var arr = new Array(10);
            alert(checkedValues);
            alert("number of values in it " +checkedValues.length);
            if (checkedValues.length > 1) {

                alert("I am inside if ");
                 arr = checkedValues.split(',');

                alert("I am done with the split ");
            }
            else {
                arr = checkedValues;
                alert("No split needed ");
            }





               $.getJSON('@Url.Action("testcata", "home")' +  + '?Type=' + "@(Session["typ"])" + "&city=" + "@(Session["cit"])" + "&chkd=" + checkedValues,


            function (data) {

                           //code
                        })

In controller :
 public ActionResult testcata(string Type, int? city, int[] chkd)
    {
      //code
    }
for(变量i=0;i
看看:

它返回一个准备好JSON的数组,如下所示:

var checkedValues = $('.required:checked').serializeArray();
试一试


JSFIDLE

使用控制台日志而不是警报。您可以显示html吗?
checkedValues
已经是一个数组。您想拆分什么?您知道jquery的.map函数返回一个数组吗@onetrickpony-那么为什么控制器中的方法将null作为多个选定检查值的参数?我在函数中有一个int[]chkd参数。它显示为空。您应该在答案中包含需要更改的内容,以实现OP正在尝试的内容。当我选中复选框,然后运行不确定的复选框时,
值数组:真值数组长度:1
值数组:真,值的真实数组长度:2
,等等。记录到JSFIDLE的
控制台。
var checkedValues = $('.required:checked').serializeArray();
[
  {
    name: "a",
    value: "1"
  },
  {
    name: "b",
    value: "2"
  },
  {
    name: "c",
    value: "3"
  },
  {
    name: "d",
    value: "4"
  },
  {
    name: "e",
    value: "5"
  }
]
// array of values
var arr = [];
$(".required")
    .on("change", function (e) {
    // `checked` `.required` elements
    var checkedValues = $(this).prop("checked");
    // `if` `checkedValues` (any `required` elements `checked`) , continue
    if (checkedValues) {
        // populate `arr` with `.required` `checked` values
        arr.push(checkedValues);
        // do stuff with `arr`
        // `console.log` values in `arr` , `arr` length
        console.log("array of values: " + arr
                    , "array of values length: " + arr.length);
    };
});