$('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
?
$('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
?
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();