如何传入多个选择的数组?

时间:2015-11-17 15:31:19

标签: javascript select serialization

我使用serialize(),但数据不会在同一个数组中传输。

function tableoptionmain() {

var msg   = $('#list-optionform').serialize();
$.ajax({
    type: 'POST',
    async: true,
    url: 'includes/parts/list/table/main-check.php',

    data: msg,

    beforeSend: function() {
        $('#listtable-parent').empty().html('<img style="margin: auto; display: block;" src="http://tbooklist.org/includes/front/img/loader/loaderIcon.gif" />');
    },
    success: function(data) {
        $('#listtable-parent').empty().html(data);
    }
});
};

我有这样的事情:

name1: data1
name1: data2

我想得到这样的东西:

name1: data1, data2

我怎样才能做到这一点?

修改 像这样的HTML

<form method="" id="list-optionform">
<select name="name1" multiple="multiple" id="name1">
  <option value="data1">data1</option>
  <option value="data2">data2</option>
  <option value="data3">data3</option>
</select>
<a href="#" onClick="tableoptionmain(); return false;">btn</a>
</form>

如果您选择多个选项,则只获取最后一个选项

1 个答案:

答案 0 :(得分:0)

    function tableoptionmain() {

    var msg   = $('#list-optionform').serialize();
        console.log(msg);
       // split the message string by &
        var arr = msg.split("&");
        console.log(arr);

        var str = "name1 : ";
        var len = arr.length;

        for(var  i= 0;i < len ; i++){
        // split each individual arr element by =
            var temp = arr[i].split("=");
            // add data to str
            str+= temp[1]+" , ";
        }
        // remove the last ,
        str = str.slice(0,str.lastIndexOf(" , "));
        console.log(str);

   ...  rest of the code including ajax call
    }