简体   繁体   中英

HTML form data to JSON format

I am trying to post some data from an HTML form to an webserver. Requirement is, The POST data should be a JSON data. The expected JSON from server is

{
    "version": "1.0.1",
    "sensors": [
        {
            "sensor": "sensorID",
            "output": [
                {
                    "name": "sensorName",
                     "type": "sensorType"
                }
            ]
        }
    ]
}

were sensorID , sensorName , sensorType corresponds to the input fields from HTML form. Others should be as it is. My code is:

<html>
   <head>
   <script src="http://code.jquery.com/jquery-latest.min.js"></script>
   </head>
  <body>
    <h2>Create Sensor</h2>
    <form id="form">
    <form enctype='application/json'>
      <input name='version' value='1.0.1'>
      <input name='sensors[0][sensor]' value=''>
      <input name='sensors[0][output][0][name]' value=''>
      <input name='sensors[0][output][0][type]' value=''>
      <br>
      <input id="input" type="submit" name="submit" value="Create Sensor" />
    </form>
    <script>
$.ajaxSetup({
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

$(document).ready(function () {
    $('#input').click(function () {
        var send = JSON.stringify($("#form").serializeArray());
        alert(send);
        $.ajax({
            url: "http://posttestserver.com/post.php",

            type: "POST",
            data: send,
            success: function (send, status, jqXHR) {
                alert(JSON.stringify(send));
            },

            error: function (jqXHR, status) {
                alert(JSON.stringify(jqXHR));
            }
        });
        return false;
    });
});
    </script>
   </body>
</html>

I am having this output:

[{
    "name": "version",
    "value": "1.0.1"
}, {
    "name": "sensors[0][sensor]",
    "value": ""
}, {
    "name": "sensors[0][output][0][name]",
    "value": ""
}, {
    "name": "sensors[0][output][0][type]",
    "value": ""
}]

Can anyone please Help me out? I am trying hard. But as I am new to this, probably missing something that's why not able to solve this problem. It will be very helpful for me if anyone please guide me regarding this. Thanks in advance.

Form your own JSON rather than using $("#form"); , Like

     var sensorArr=new Array();
    //push your values to SensorArr
     var data= {
        "version": $("input[name='version']").val(),
        "sensors": [
            {
                "sensor": "sensorID",
                "output": sensorArr;
            }
        ]
    }

and send this data to AJAX

how about change html?

<input name='sensors[0][sensor]' value=''>

to

<input class="d_sensors" name='sensor' value=''>

read javascript

var data = {};
data['version'] = $("input[name='version']").val();
data['sensors'] = [];
var sensorsList = $(".d_sensors");
for (var i = 0; i < sensorsList.length; i++) {
  var $item = sensorsList.eq(i);
  var sensor = {};
  sensor['sensor'] = $item.val();
  sensor['output'] = [];
// do same way
}

Will in your case you need to setup JSON Object , why !!

because when Html inputs submitted as Array each key mean new array you cannot group them in one object as you requested , to do this you need to use custom javascript array

this is full working example to your case

1- first : remove array name from your inputs to be like this :

  <input name='sensors_sensor' value=''>
  <input name='sensors_name' value=''>
  <input name='sensors_type' value=''>

2- second : add this object inside form post request ( AJAX )

  var fromData = { 
  "version"  : $('input[name=version]').val(),
  "sensors"  : [ { "sensor" : $('input[name=sensors_name]').val(),
                   "output" : [{  "name" : $('input[name=sensors_name]').val() , 
                                  "type": $('input[name=sensors_type]').val()}] } ],

  };

3- third : if you like to add more inputs just add it inside the formData object

4- finally : add formData object to your Ajax form and enjoy

$.ajax({
            url: "http://posttestserver.com/post.php",

            type: "POST",
            data: formData,
            success: function (send, status, jqXHR) {
                alert(JSON.stringify(send));
            },

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