简体   繁体   中英

Can I post JSON without using AJAX?

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"

  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 ( eg 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. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM