1

想知道我必须做些什么来转换我当前正在发送的数据(使用serializeArray()

data[0][name]:title
data[0][value]:This is my sample title
data[1][name]:description
data[1][value]:This is an (optional) description but I'm filling it out as an example
data[2][name]:source
data[2][value]:http://www.cnn.com
data[3][name]:category
data[3][value]:animals

改为这样发送:

data[title]:This is my sample title
data[description:This is an (optional) description but I'm filling it out as an example
data[source]:http://www.cnn.com
data[category]:animals

代码:

$(function() {
    $('input[type="submit"]').click(function() {
        var $data = $('#js-serialize').serializeArray();
        console.log($data);
        $.post('/echo/json', {
            'data': $data
        }, function(data) {
            console.log(data);
        }, 'json');
        return false;

    });

});

<form id="js-serialize">
<input name="title" placeholder="title" />
<input name="description" placeholder="description" />
<input name="source" placeholder="source" />
<input name="category" placeholder="category"/>
<input type="submit" name="submit" />
</form>​

演示:

http://jsfiddle.net/someprimetime/bnPwN/5/

4

2 回答 2

0

您似乎正在寻找对象表示而不是数组。

jQuery 不支持serializeObject()开箱即用之类的东西。然而,这个插件似乎完全符合您的要求。

于 2012-08-21T19:39:28.307 回答
0

未经测试,但:

function serializeObject(serializedArray){
    var serializedObj={};
    serializedArray.forEach(function(i){
       serializedObj[i.name]=i.value;       
    });
    return serializedObj;
}
于 2014-03-27T13:42:36.877 回答