最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I post JSON without using AJAX? - Stack Overflow

programmeradmin3浏览0评论

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 ajax).

I know this is possible, but I can't find any literature on it. Ideas?

(I am using jQuery, if that makes it easier)

EDIT: while all of these answers so far answer the question, I should have included that I want an "content type" of "application/json"

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 ajax).

I know this is possible, but I can't find any literature on it. Ideas?

(I am using jQuery, if that makes it easier)

EDIT: while all of these answers so far answer the question, I should have included that I want an "content type" of "application/json"

Share Improve this question edited Dec 13, 2010 at 15:42 Aaron Scruggs asked Dec 13, 2010 at 14:24 Aaron ScruggsAaron Scruggs 7121 gold badge4 silver badges11 bronze badges 4
  • 5 What the hell is a "roundtrip"? – Luca Matteis Commented Dec 13, 2010 at 14:29
  • Why don't you want to send data using AJAX? – Crozin Commented Dec 13, 2010 at 14:41
  • 3 @Crozin AJAX is not usefull 100% of the cases. If you need a different response like downloading a file dynamically... remember JS limitations – Leandro Bardelli Commented Oct 10, 2013 at 18:03
  • I know this question is kinda old, but I had the same requirement and found a proper solution that was not in the answers, so I added it. – Unicornist Commented Apr 3, 2019 at 16:17
Add a comment  | 

5 Answers 5

Reset to default 7
  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

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.

<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>

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.

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)

  1. 暂无评论