在jQuery中创建动态formdata

时间:2014-12-10 11:20:08

标签: javascript jquery

我有一个表单,我想将表单数据发送到服务器端。但是我无法在jquery中创建动态查询字符串。我有这样的html:

<div>
    <ul class="items" id ="test">
        <li class="test" id="11" attr ="11"></li>
        <li class="test" id="12" attr ="12"></li>
        <li class="test" id="13" attr ="13"></li>
        <li class="test" id="14" attr ="14"></li>

    </ul>
    <ul class="items" id ="test1">
        <li class="test" id="21" attr ="21"></li>
        <li class="test" id="22" attr ="22"></li>
        <li class="test" id="23" attr ="23"></li>
        <li class="test" id="24" attr ="24"></li>
    </ul>
     <ul class="items" id ="test2">
        <li class="test" id="31" attr ="31"></li>
        <li class="test" id="32" attr ="32"></li>
        <li class="test" id="33" attr ="33"></li>
        <li class="test" id="34" attr ="34"></li>
    </ul>
</div>

我在jQuery中完成了这个。

var ids=[];
$('ul.items').each(function(){
    var id = $(this).attr('id').replace(/test/,'');
    var tmp_arr=[];
    $($(this).find("li")).each(function(){
        var attr_val = $(this).attr("attr");
        tmp_arr.push({$(this).attr('id')});
    });
    ids.push(tmp_arr);
});

但我想要的jquerystring就像这样

{
    "test"=>{
        "ids"=>['11','12','13','14'],
        "attr=>['11','12','13','14']"
        },
    "test1"=>{
        "ids"=>['21','22','23','24'],
        "attr=>['21','22','23','24']"
        },
    "test2"=>{
        "ids"=>['31','32','33','34'],
        "attr=>['31','32','33','34']"
        }
} 

我们如何创建这个jQuery请帮帮我

1 个答案:

答案 0 :(得分:2)

尝试这样的事情。 Array.prototype.map在这里很有用:

var data = {};
$('.items').each(function() {
    var children = $(this).children().toArray();
    data[this.id] = {
        ids: children.map(function(el) {
            return el.id;
        }),
        attrs: children.map(function(el) {
            return el.getAttribute('attr');
        })
    };
});

alert(JSON.stringify( data, null, 4 ));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <ul class="items" id ="test">
        <li class="test" id="11" attr ="11"></li>
        <li class="test" id="12" attr ="12"></li>
        <li class="test" id="13" attr ="13"></li>
        <li class="test" id="14" attr ="14"></li>

    </ul>
    <ul class="items" id ="test1">
        <li class="test" id="21" attr ="21"></li>
        <li class="test" id="22" attr ="22"></li>
        <li class="test" id="23" attr ="23"></li>
        <li class="test" id="24" attr ="24"></li>
    </ul>
     <ul class="items" id ="test2">
        <li class="test" id="31" attr ="31"></li>
        <li class="test" id="32" attr ="32"></li>
        <li class="test" id="33" attr ="33"></li>
        <li class="test" id="34" attr ="34"></li>
    </ul>
</div>