使用serializeJSON从HTML表单格式化JavaScript对象

时间:2021-06-29 10:20:35

I am having some issues getting the data out of my HTML form and into the proper JSON format that is required by the server that I'm sending to. I've tried following along this guide I found for extracting the data and formatting as JavaScript Object, but I cannot get the output to match what I'll need to send off.

我有一些问题从我的HTML表单中获取数据,并进入我要发送到的服务器所需的正确JSON格式。我已经尝试按照我发现的用于提取数据和格式化为JavaScript对象的指南,但我无法得到输出以匹配我需要发送的内容。

I have been able to get the question key that I need, along with it's proper value, but have been unable to add the proper labeling.

我已经能够得到我需要的问题密钥,以及它的正确值,但是无法添加适当的标签。

Current Output:

电流输出:

{"Question1":"Yes",
"Question2":"No",
"Question3":"1",
"Question4":"Female"}

Required Output:

要求输出:

{
"Key":"Question1",
"Value":"Yes"
 }, {
"Key":"Question2",
"Value":"No"
 }, {
"Key":"Question1",
"Value":"No"
 }, {
 "Key":"Question4",
 "Value":"Female"
 }

(I included the script for the serializeJSON plugin to get the snippet to work)

(我包含了serializeJSON插件的脚本以使代码段工作)

$(function(){
var $select = $(".1-100");
for (i=1;i<=100;i++){
    $select.append($('<option></option>').val(i).html(i))
 }
});	

function submitForm () { 


var result = [];
$.each($('form').serializeArray(), function(i,field){
result.push({"Key": field.name, "Value":field.value})
 
});
  
var formData = JSON.stringify($(result));	
	console.log(formData);
};
  
	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="survey" method="post">
	<div class="form-group">
 	<div class="col-sm-3 selectContainer">
		
	 <label class="control-label" >First Question</label>
  		<select class="form-control" name="QuestionKey1">
    		<option name="Value" value="Yes" selected>Yes</option>
    		<option name="Value" value="No">No</option>
  		</select>
	</div>	
		
	<div class="col-sm-3 selectContainer">	
  		<label class="control-label">Second Question</label>
  			<select class="form-control" name="QuestionKey2">
    			<option name="Value" value="Yes">Yes</option>
    			<option name="Value" value="No" selected>No</option>
 			 </select>
		</div>
				
	<div class="col-sm-2 selectContainer">
		  <label class="control-label">Third Question</label>	
			<select class="form-control 1-100" id="age" name="QuestionKey3"></select>
    </div>
		
		<div class="col-sm-2">
		 <label class="control-label">Fourth Question</label>	
			 <label class="radio-inline">
			 	<input type="radio" name="QuestionKey4" value="Female" />Female
			  </label>
			  <label class="radio-inline">
				 <input type="radio" name="QuestionKey4" value="Male" />Male
			  </label>	
		
		</div>	
		</div>				
	<input value="Submit" type="button" onclick="submitForm()">	
</form>

Any tips or advice would be greatly appreciated. Thank you.

任何提示或建议将不胜感激。谢谢。

Edit - After following one of the examples sent I am ending up with my output looking like this:

编辑 - 在发送其中一个示例之后,我的输出结果如下:

{"0":{"Key":"QuestionKey1","Value":"Yes"},"1": 
{"Key":"QuestionKey2","Value":"No"},"2": 
{"Key":"QuestionKey3","Value":"1"},"3": 
{"Key":"QuestionKey4","Value":"Male"},"length":4}

I've also modified my snippet to reflect the changes that got me to this point.

我还修改了我的代码片段,以反映让我达到这一点的变化。

2 个解决方案

#1


3  

Try something like this: (no need for that plugin), using http://api.jquery.com/serializeArray/

尝试这样的事情:(不需要那个插件),使用http://api.jquery.com/serializeArray/

var result = [];    
$.each($('form').serializeArray(), function(i, field){
    result.push({"Key": field.name, "Value":field.value})
});

finally call JSON.stringify if you need it in string format

如果你需要字符串格式,最后调用JSON.stringify

#2


2  

Firstly note that the on* event attributes are outdated. You should use unobtrusive event handlers instead. Also, when dealing with forms you should hook to the submit event of the form element, not the click of the submit button. This is for accessibility purposes.

首先请注意on *事件属性已过时。您应该使用不显眼的事件处理程序。此外,在处理表单时,您应该挂钩表单元素的submit事件,而不是单击提交按钮。这是为了便于访问。

With regard to your actual issue, you don't need to use the serializeJSON plugin. jQuery's own serializeArray() method gets you close to the data format you need, however it returns an array of objects with name and value keys, not a single object keyed by the name of the input itself. To fix that you can loop through the array, something like this:

关于您的实际问题,您不需要使用serializeJSON插件。 jQuery自己的serializeArray()方法使您接近所需的数据格式,但它返回一个带有名称和值键的对象数组,而不是一个由输入本身名称键入的对象。要解决这个问题,你可以循环遍历数组,如下所示:

$(function() {
  var $select = $(".1-100");
  for (i = 1; i <= 100; i++) {
    $select.append($('<option></option>').val(i).html(i))
  }

  $('#survey').on('submit', function(e) {
    e.preventDefault();
    
    var obj = {};
    $(this).serializeArray().forEach(function(arr) {
      obj[arr.name] = arr.value;
    })
    
    console.log(obj);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="survey" method="post">
  <div class="form-group">
    <div class="col-sm-3 selectContainer">
      <label class="control-label">First Question</label>
      <select class="form-control" name="QuestionKey1">
        <option name="Value" value="Yes" selected>Yes</option>
        <option name="Value" value="No">No</option>
      </select>
    </div>
    <div class="col-sm-3 selectContainer">
      <label class="control-label">Second Question</label>
      <select class="form-control" name="QuestionKey2">
        <option name="Value" value="Yes">Yes</option>
        <option name="Value" value="No" selected>No</option>
      </select>
    </div>
    <div class="col-sm-2 selectContainer">
      <label class="control-label">Third Question</label>
      <select class="form-control 1-100" id="age" name="QuestionKey3"></select>
    </div>

    <div class="col-sm-2">
      <label class="control-label">Fourth Question</label>
      <label class="radio-inline">
        <input type="radio" name="QuestionKey4" value="Female" />Female
      </label>
      <label class="radio-inline">
        <input type="radio" name="QuestionKey4" value="Male" />Male
      </label>
    </div>
  </div>
  <button type="submit">Submit</button>
</form>

#1


3  

Try something like this: (no need for that plugin), using http://api.jquery.com/serializeArray/

尝试这样的事情:(不需要那个插件),使用http://api.jquery.com/serializeArray/

var result = [];    
$.each($('form').serializeArray(), function(i, field){
    result.push({"Key": field.name, "Value":field.value})
});

finally call JSON.stringify if you need it in string format

如果你需要字符串格式,最后调用JSON.stringify

#2


2  

Firstly note that the on* event attributes are outdated. You should use unobtrusive event handlers instead. Also, when dealing with forms you should hook to the submit event of the form element, not the click of the submit button. This is for accessibility purposes.

首先请注意on *事件属性已过时。您应该使用不显眼的事件处理程序。此外,在处理表单时,您应该挂钩表单元素的submit事件,而不是单击提交按钮。这是为了便于访问。

With regard to your actual issue, you don't need to use the serializeJSON plugin. jQuery's own serializeArray() method gets you close to the data format you need, however it returns an array of objects with name and value keys, not a single object keyed by the name of the input itself. To fix that you can loop through the array, something like this:

关于您的实际问题,您不需要使用serializeJSON插件。 jQuery自己的serializeArray()方法使您接近所需的数据格式,但它返回一个带有名称和值键的对象数组,而不是一个由输入本身名称键入的对象。要解决这个问题,你可以循环遍历数组,如下所示:

$(function() {
  var $select = $(".1-100");
  for (i = 1; i <= 100; i++) {
    $select.append($('<option></option>').val(i).html(i))
  }

  $('#survey').on('submit', function(e) {
    e.preventDefault();
    
    var obj = {};
    $(this).serializeArray().forEach(function(arr) {
      obj[arr.name] = arr.value;
    })
    
    console.log(obj);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="survey" method="post">
  <div class="form-group">
    <div class="col-sm-3 selectContainer">
      <label class="control-label">First Question</label>
      <select class="form-control" name="QuestionKey1">
        <option name="Value" value="Yes" selected>Yes</option>
        <option name="Value" value="No">No</option>
      </select>
    </div>
    <div class="col-sm-3 selectContainer">
      <label class="control-label">Second Question</label>
      <select class="form-control" name="QuestionKey2">
        <option name="Value" value="Yes">Yes</option>
        <option name="Value" value="No" selected>No</option>
      </select>
    </div>
    <div class="col-sm-2 selectContainer">
      <label class="control-label">Third Question</label>
      <select class="form-control 1-100" id="age" name="QuestionKey3"></select>
    </div>

    <div class="col-sm-2">
      <label class="control-label">Fourth Question</label>
      <label class="radio-inline">
        <input type="radio" name="QuestionKey4" value="Female" />Female
      </label>
      <label class="radio-inline">
        <input type="radio" name="QuestionKey4" value="Male" />Male
      </label>
    </div>
  </div>
  <button type="submit">Submit</button>
</form>