简体   繁体   中英

Post JSON value without ajax

I have a simple HTML form which collects four different values. I would like to post the collected data to an API server in JSON format.

 <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 (); 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. Then use JSON.strigify to convert that to a JSON blob which will be part of the ajax call.

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.

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