Can I post JSON without using AJAX?

后端 未结 5 774
不思量自难忘°
不思量自难忘° 2021-01-12 15:35

I have some data, lets say:

var dat = JSON.stringify(frm.serializeArray())

I want to submit this to the server using a roundtrip (aka, non

相关标签:
5条回答
  • 2021-01-12 16:02

    In another answer someone mentioned a W3 working draft which is outdated now and the newer version of the document says we can use enctype="application/json" attribute for the form and it will send the whole form fields as properties of an object.

    It is still unclear to me how to send an array though, but refering to the above document you can send an object simply as:

    <form enctype='application/json'>
      <input name='name' value='Bender'>
      <select name='hind'>
        <option selected>Bitable</option>
        <option>Kickable</option>
      </select>
      <input type='checkbox' name='shiny' checked>
    </form>
    
    // produces {"name": "Bender", "hind": "Bitable", "shiny": true}
    

    I can't copy the whole doc here, so check out the document to see how to create more complex objects using array notation and sparsing arrays in input field names.

    To create the form out of your object, you have to make a series of input elements, that produces the same JSON object you have in hand. You can either do it manually, or if your object is large enough, you can use a code snippet to convert your object to the desired input elements. I ended up with something like the code below as the base. You can change it to your need (e.g. make the form hidden or even produce more diverse input field types with styles for different property types for a real proper form)

    (function () {
      const json = {
        bool: false,
        num: 1.5,
        str: 'ABC',
        obj: {b:true, n: .1, s: '2', a: [1, '1']},
        arr: [
          true, 500.33, 'x', [1, 2],
          {b:true, n: .1, s: '2', a: [1, '1']}
        ]
      };
    
      const getFieldHTML = (value, name) => {
        if (name||name===0) switch (typeof value) {
          case 'boolean': return `<input type="checkbox" name="${name}" ${value?'checked':''}>\n`;
          case 'number': return `<input type="number" name="${name}" value="${value}">\n`;
          case 'string': return `<input type="text" name="${name}" value="${value}">\n`;
        }
        return '';
      };
      
      const getFieldsHTML = (value, name) => {
        const fields = [];
        if (value instanceof Array)
          fields.push(...value.map((itemValue, i) => 
            getFieldsHTML(itemValue, name+'['+i+']')
          ));
        else if (typeof value === "object")
          fields.push(...Object.keys(value).map(prop =>
            getFieldsHTML(
              value[prop], //value is an object
              name?(name+'['+prop+']'):prop
            )
          ));
        else
          fields.push(getFieldHTML(value, name));
        return fields.join('');
      };
    
      const fieldsHTML = getFieldsHTML(json);
    
      const frm = document.createElement('form');
      frm.enctype = 'application/json';
      frm.method = 'POST';
      frm.action = 'URL GOES HERE';
      frm.innerHTML = fieldsHTML;
    
      console.log(fieldsHTML);
      console.log(frm)
    })();
    Check your browser's console to inspect the created form DOM and its children.

    0 讨论(0)
  • 2021-01-12 16:03
    1. Create an HTML form with unique "id" attribute. You can hide it using CSS "display:none". Also fill the action and method attributes.
    2. Add a text or hidden input field to the form. make sure you give it a meaningful "name" attribute. That's the name that the server would get the data within.
    3. Using JQuery (or plain old javascript) copy the variable "dat" into the input field
    4. Submit the form using script
    0 讨论(0)
  • 2021-01-12 16:06

    There is a working draft to support the so called HTML-JSON-FORMS, see: http://www.w3.org/TR/2014/WD-html-json-forms-20140529/

    So far use ajax or send the json into an input text field.

    0 讨论(0)
  • 2021-01-12 16:06

    You would need to assign the json string to an input's value inside a form tag in order for it to get POSTed to the server (either by the user submitting the form or by clicking the submit button programmatically).

    Alternatively from javascript you could use window.location to send the variable as part of a GET request.

    0 讨论(0)
  • 2021-01-12 16:07
    <form action="xxx.aspx" method="POST">
      <input type='hidden' id='dat' />
    
      <!-- Other elements -->
    </form>
    
    <script type='text/javascript'>
      $('#dat').val(JSON.stringify(frm.serializeArray()));
    </script>
    
    0 讨论(0)
提交回复
热议问题