문제

Was wondering what I'd have to do to convert my data that is currently being sent like this (using 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

To send like this instead:

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

Code:

$(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>​

Demo:

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

도움이 되었습니까?

해결책

It seems that you're looking for an object representation instead of an array.

jQuery does not support something like serializeObject() out of the box. This plugin, however, seems to do exactly what you want.

다른 팁

Not tested, but:

function serializeObject(serializedArray){
    var serializedObj={};
    serializedArray.forEach(function(i){
       serializedObj[i.name]=i.value;       
    });
    return serializedObj;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top