簡體   English   中英

如何解析表單數據以在jQuery中使用JSON?

[英]How to parse form data to work with JSON in jQuery?

 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函數發送給控制器。 沒有顯示alert(“我已完成拆分”)。 請幫我。

看看.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"
  }
]

split對字符串起作用。您可以split on each array index而不是whole array使用split on each array index

如果您真的想分割數組checkedValues則循環遍歷該數組,然后use split on each index

像這樣:

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

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

}

嘗試

// 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM