开发者

jQuery serialize and unserialize

I want to serialize and un-serialize a form with jQuery.

How can I get all attributes of all 开发者_运维知识库elements in a serialized way?


.serialize() will map your input controls that have a name attribute defined into a standard query string:

foo=bar&bar=foo&and=soon

That kind of string is easy accesible in almost every "backend" programming language.

If you need to serialize object information, use JSON.

var obj = {
    foo:  'bar',
    more: 'etc
};

serialize this with window.JSON.stringify(obj);. To unserialize such a JSON string, use window.JSON.parse(str);, which returns a javascript object.

Many languages support this principle.


2020 solution

serialize()

Is included in jQuery itself for this very purpose https://api.jquery.com/serialize/

$('#someKind .ofASelectorForYour form').serialize(); (returns serialized string)

unserialize()

Is not included in jQuery, but, the documentation says

The .serialize() method creates a text string in standard URL-encoded notation.

...so, in 2020, we can leverage the URLSearchParams interface:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://url.spec.whatwg.org/#interface-urlsearchparams

function unserialize(serializedData) {
    let urlParams = new URLSearchParams(serializedData); // get interface / iterator
    let unserializedData = {}; // prepare result object
    for (let [key, value] of urlParams) { // get pair > extract it to key/value
        unserializedData[key] = value;
    }

    return unserializedData;
}

(returns object of unserialized key => value pairs)
A one-liner for one-time usage extractor (your data in sData, result in unsData):

let prms = new URLSearchParams(sData); let unsData = {}; for (let [k, v] of prms) unsData[k] = v;

BTW: as MDN docs say,

following two lines are equivalent:
for (const [key, value] of mySearchParams) {}
for (const [key, value] of mySearchParams.entries()) {}


jQuery has a serialize function.

$("#form").serialize(); // Returns serialized string

Reference: http://api.jquery.com/serialize/


If you want unserialize you must create a function like this;

function unserialize(data) {
    data = data.split('&');
    var response = {};
    for (var k in data){
        var newData = data[k].split('=');
        response[newData[0]] = newData[1];
    }
    return response;
}

this function inverse serialize() and return a json data.


All elements in the form will be sent along if using the $('form').serialize();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜