Can I post JSON without using AJAX?

后端 未结 5 773
不思量自难忘°
不思量自难忘° 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:

    // 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 `\n`;
          case 'number': return `\n`;
          case 'string': return `\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.

提交回复
热议问题