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

时间:2014-09-19 12:54:58

标签: javascript jquery json forms

 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
    }

我正在尝试获取已检查的复选框的值并将它们存储在数组中,然后通过json函数将其发送到控制器。警告("我已完成拆分")未显示。请帮帮我。

3 个答案:

答案 0 :(得分:1)

查看.serializeArray()

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

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

[
  {
    name: "a",
    value: "1"
  },
  {
    name: "b",
    value: "2"
  },
  {
    name: "c",
    value: "3"
  },
  {
    name: "d",
    value: "4"
  },
  {
    name: "e",
    value: "5"
  }
]

答案 1 :(得分:0)

split适用于字符串。您可以使用split on each array index而不是whole array

如果你真的想拆分数组checkedValues,那么循环遍历这个数组,然后use split on each index

像这样:

for( var i=0; i< checkedValues.length;i++){

var arr = checkedValues[i].split(',');
// use arr for requrement.

}

答案 2 :(得分:0)

尝试

// 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);
    };
});

jsfiddle http://jsfiddle.net/guest271314/d332nfkh/