How do I send a complex JSON object from an HTML form using SYNCHRONOUS page POST?

后端 未结 4 2080
清歌不尽
清歌不尽 2021-01-15 11:21

My server is using ServiceStack and would like to receive some data like this:

{
    Customer: {
        Company: \"TheCompany\",
        RegionCode: \"AU_NS         


        
4条回答
  •  终归单人心
    2021-01-15 12:04

    I ran into the same thing here where I was using NodeJS and an Express Server. I wanted to post a complex JSON object that I had built as the user made selections client side. I then attached an onClick event to a button that called my SubmitForm function.

    Your data can be any JSON object. Just be sure to parse it server side.

    function Param(name, value){
        var hiddenField = document.createElement('input');
        hiddenField.setAttribute('type', 'hidden');
        hiddenField.setAttribute('name', name);
        hiddenField.setAttribute('value', value);
        return hiddenField;
    }
    
    function SubmitForm(data){
        var form = document.createElement('form');
        form.setAttribute('method', 'post');
        form.setAttribute('action', '/route');
        form.appendChild(Param('data', JSON.stringify(data)));
    
        document.body.appendChild(form);
        form.submit();    
    }
    

    Additionally, this is pure javascript. No hidden HTML or jQuery here for those of you who prefer to remove the overhead.

提交回复
热议问题