简体   繁体   English

我可以在不使用AJAX的情况下发布JSON吗?

[英]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). 我想使用往返(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) (我正在使用jQuery,如果这样更容易)

EDIT: while all of these answers so far answer the question, I should have included that I want an "content type" of "application/json" 编辑:虽然所有这些答案到目前为止回答了问题,我应该包括我想要“内容类型”的“application / json”

  1. Create an HTML form with unique "id" attribute. 创建具有唯一“id”属性的HTML表单。 You can hide it using CSS "display:none". 您可以使用CSS“display:none”隐藏它。 Also fill the action and method attributes. 还要填充操作和方法属性。
  2. Add a text or hidden input field to the form. 向表单添加texthidden输入字段。 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 使用JQuery(或普通的旧javascript)将变量“dat”复制到输入字段中
  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/ 有一个工作草案支持所谓的HTML-JSON-FORMS,请参阅: http//www.w3.org/TR/2014/WD-html-json-forms-20140529/

So far use ajax or send the json into an input text field. 到目前为止使用ajax或将json发送到输入文本字段。

<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). 您需要将json字符串分配给表单标记内的输入值,以便将其发送到服务器(通过用户提交表单或通过编程方式单击提交按钮)。

Alternatively from javascript you could use window.location to send the variable as part of a GET request. 或者从javascript中,您可以使用window.location将变量作为GET请求的一部分发送。

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. 在另一个答案中有人提到W3工作草案现在已经过时,文档新版本说我们可以对表单使用enctype="application/json"属性,它会将整个表单字段作为对象的属性发送。

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. 我无法复制整个文档,因此请查看文档 ,了解如何使用数组表示法创建更复杂的对象,并在输入字段名称中使用sparsing数组。

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. 要从对象创建表单,您必须创建一系列输入元素,这些元素将生成您手头的相同JSON对象。 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. 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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