开发者

How to post a complex HTML form as JSON?

I have a very complex form in a web page. User actually builds up a complex object. The UI is handled using jQuery (showing, hiding sections, duplicating and deleting sub-forms,...).

Simply posting the form upon user submission, although possible, doesn't seem the best solution开发者_运维百科: It would be hard to makeup unique names for fields (there can be arrays of objects) and to decode the whole stuff on server side.

I guess I should rather post a JSON representation of the object. How do I do that?

I'm not trying to make an ajax call. I want to submit the form but using JSON instead of an usual application/x-www-form-urlencoded form.

FWIW, the backend is ASP.NET MVC.

TIA,


Serialise to JSON using script...

Although this answer uses Ajax, you could instead write the serialised string to an input[type=hidden] in your form

Serializing to JSON in jQuery


You can try this:

$("form").submit(function()
{
    //Checking data here:
    $("input").each(function(i, obj)
    {
    });
    alert($(this).serialize());
    alert(toJSON($(this).serializeArray()));
    //return false;
});

function toJSON(obj)
{
    var json = '({';
    $.each(obj, function(k,v){
    var q = typeof v == 'string' ? ~v.indexOf("'") ? '"' : "'" : '';
    if (typeof v == 'object')
    v = toJSON(v).slice(0,-1).substr(1);
    json+= k + ':'+ q + v + q + ',';
    });
    return json.slice(0,-1)+'})';
};

My fiddle: http://jsfiddle.net/Achilleterzo/6Zj6n/


If you are using jquery you can look into these two functions .serialize() and .serializeArray()

These functions will help you get the form data, without you having to manually iterate.


Use the jquery form plugin to submit the form via AJAX. For duplicate field names the default way is usually appending [] to the name - most server-side languages then create an array containing all submitted values. Depending on the language it might also happen without the [] but I'm sure MSDN will help you since you are using ASP.NET for your backend.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜