开发者

Serialize form to and from JSON

开发者 https://www.devze.com 2023-01-13 05:48 出处:网络
I want to serialize a form into json, process the json object, then reserialize it to send to a php script via ajax.

I want to serialize a form into json, process the json object, then reserialize it to send to a php script via ajax.

Here is a rough example of what I want to do:

s = $('.dia_req_form').serialize();
j = //convert s to json ...HOW??
i开发者_Go百科f(j.name)
{
    alert("you must enter a name");
}
if(selectedID)
{
    j.id = selectedID;
}
s = //serialize j ...HOW??

You can see the 2 parts that say HOW??


You can use .serializeArray() and $.param() like this:

//validate here
var obj = $('.dia_req_form').serializeArray();
if(selectedID) {
  obj.push({ name: 'id', value: selectedID });
}
var s = $.param(obj); //s can be used for submission

Internally, .serialize() is really equivalent to $.param($(this).serializeArray()), so all this is doing is breaking the steps apart, adding an item if needed.

.serializeArray() is an array of objects with 2 properties (name and value), all we're doing is adding some object to the array if needed, then calling $.param() to make it a string.


You can use this lib, $.serializeObject is a variant of existing $.serialize method which, instead of encoding form elements to string, converts form elements to a valid JSON object which can be used in your JavaScript application.

https://github.com/hongymagic/jQuery.serializeObject

0

精彩评论

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