简体   繁体   English

发布不带Ajax的JSON值

[英]Post JSON value without ajax

I have a simple HTML form which collects four different values. 我有一个简单的HTML表单,该表单收集四个不同的值。 I would like to post the collected data to an API server in JSON format. 我想将收集的数据以JSON格式发布到API服务器。

 <body> <h2>Form</h2> <form action="/endpoints" method="post" onsubmit="return profile();"> MAC Address:<input type="text" id="mac" name="mac" size="12"/> <br/>Select Catagory:<br/> <select name="catagory" id="catagory"> <option value="SmartDevice">SmartDevice</option> <option value="Printer">Printer</option> <option value="Printer">Printer</option> </select> <br/>Select Family:<br/> <select name="family" id="family"> <option value="Android">Android</option> <option value="Ricoh">Ricoh</option> <option value="Canon">Canon</option> </select> <br/>Name:<br/> <select name="name" id="name"> <option value="Android">Android</option> <option value="Ricoh Multifunction Printer">Ricoh Multifunction Printer</option> <option value="Canon Printer">Canon Printer</option> </select> <input type="submit" style="width: 200px;" id="submit" onclick="return profile();"> <script type="text/javascript"> {literal} function profile (){ var addr = document.getElementsByName("mac")[0].value; var str_array = addr.split(','); var nam = document.getElementsByName("name")[0].value; var famil = document.getElementsByName("family")[0].value; var catagor = document.getElementsByName("catagory")[0].value; for(var i = 0; i < str_array.length; i++) { str_array[i] = str_array[i].replace(/^\\s*/, "").replace(/\\s*$/, ""); var output = '[' + JSON.stringify({mac: str_array[i], device: {category: catagor, family: famil, name: nam}}) + ']'; }; return output; } {/literal} </script> </form> </body> 

I am able to get the desired JSON output if I call profile (); 如果我调用profile(),则能够获得所需的JSON输出; in the console. 在控制台中。 But Posted data is different with all values in single line. 但是所有行中的所有值的发布数据都不同。

I expect the post data to be like: 我希望发布数据是这样的:

 [{"mac": "aabbccddeeff", "device": {"category": "Printer", "family": "Xerox", "name": "Xerox WorkCenter"}}, {"mac": "bbccddeeffaa", "device": {"category": "Printer", "family": "Xerox", "name": "Xerox WorkCenter"}}, {"mac": "ccddeeffaabb", "device": {"category": "Printer", "family": "Xerox", "name": "Xerox WorkCenter"}}]' 

Please help me and I am a newbie. 请帮助我,我是新手。 :-) :-)

First construct an output which is an Array. 首先构造一个output ,它是一个数组。 Then use JSON.strigify to convert that to a JSON blob which will be part of the ajax call. 然后使用JSON.strigify将其转换为JSON blob,这将成为ajax调用的一部分。

Also you cannot return data which is modified which is part of the form elements, you need to resort to making explicit ajax calls from JS. 同样,您不能返回作为表单元素一部分的修改后的数据,您需要诉诸于从JS进行显式ajax调用。

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

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