2

$('form').serialize() will generate something like a=1&b=2,but what I want to get is {a:1,b:2}.

How to do this?

Further more,is it possible to do this kind of job to arbitrary container like div?

2

1 Answer 1

4

jQuery doesn't support this. You'll have to use JSON.stringify, which is supported in some modern browsers, but for support in older browsers, you have to include the json2 library as a <script>

You could then have something like:

(function ($) {

    jQuery.fn.jsonSerialize = function () {
        var obj = {};
        var form = this[0];

        if (form.tagName !== "FORM") {
            return "";
        }

        $(form.elements).each(function () {
            obj[this.name] = $(this).val();
        });

        return JSON.stringify(obj);
    }

}(jQuery));

Then use as follows:

var stringified = $('#yourForm').jsonSerialize();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.