HTML/Javascript 表单 如何将表单数据序列化为 JSON 并在类中显示?

Posted

技术标签:

【中文标题】HTML/Javascript 表单 如何将表单数据序列化为 JSON 并在类中显示?【英文标题】:HTML/Javascript Form How do I serialize form data as JSON and displayed in a class? 【发布时间】:2017-05-15 16:33:46 【问题描述】:

非常直接。

当用户点击“提交”时,我需要将表单序列化并在“debug”类中显示JSON数据。

如何使用我当前的 javascript 执行此操作?

无法使用 jQuery。无法编辑 html。只有纯 Javascript。

谢谢!

HTML

<ol class="household"></ol>
    <form>
        <div>
            <label>Age
                <input type="text" name="age">
            </label>
        </div>
        <div>
            <label>Relationship
                <select name="rel">
                    <option value="">---</option>
                    <option value="self">Self</option>
                    <option value="spouse">Spouse</option>
                    <option value="child">Child</option>
                    <option value="parent">Parent</option>
                    <option value="grandparent">Grandparent</option>
                    <option value="other">Other</option>
                </select>
            </label>
        </div>
        <div>
            <label>Smoker?
                <input type="checkbox" name="smoker">
            </label>
        </div>
        <div>
            <button class="add">add</button>
        </div>
        <div>
            <button type="submit">submit</button>
        </div>
    </form>
</div>
<pre class="debug"></pre>

JS

function validate(form) 
        fail = validateAge(form.age.value)
        fail += validateRel(form.rel.value)

        if (fail == "") return true
        else 
            alert(fail);
            return false
        
    

    function validateAge(field) 
        if (isNaN(field)) return "No age was entered. \n"
        else if (field < 1 || field > 200)
            return "Age must be greater than 0. \n"
        return ""
    

    function validateRel(field) 
        if (field == "") return "Please select a relationship \n"
        return ""
    

    document.querySelector("form").onsubmit = function() 
        return validate(this)
    

    document.querySelector(".add").onclick = function(event) 
        event.preventDefault();
        createinput()
    

    count = 0;
    function createinput() 
        field_area = document.querySelector('.household')
        var li = document.createElement("li");
        var p1 = document.createElement("p");
        var p2 = document.createElement("p");
        var p3 = document.createElement("p");
        var x = document.getElementsByName("age")[0].value;
        var y = document.getElementsByName("rel")[0].value;
        var z = document.getElementsByName("smoker")[0].checked;
        if (!z) 
            z = "Non smoker \n";
         else 
            z = "Smoker \n";
        
        p1.innerHTML = x;
        p2.innerHTML = y;
        p3.innerHTML = z;
        li.appendChild(p1);
        li.appendChild(p2);
        li.appendChild(p3);
        field_area.appendChild(li);
        //removal link
        var removalLink = document.createElement('a');
        removalLink.onclick = function() 
            this.parentNode.parentNode.removeChild(this.parentNode)
        
        var removalText = document.createTextNode('Remove Field');
        removalLink.appendChild(removalText);
        li.appendChild(removalLink);
        count++
    

    // serialize form
    var data = ;
    var inputs = [].slice.call(e.target.querySelector('form'));
    inputs.forEach(input => 
        data[input.name] = input.value;
    );

【问题讨论】:

***.com/questions/22195065/… 【参考方案1】:

最短的解决方案(纯javascript):

var form = document.querySelector('form');
var data = new FormData(form);

文档:https://developer.mozilla.org/en-US/docs/Web/API/FormData

【讨论】:

【参考方案2】:

我非常了解这个表格,因为我申请了同一个职位。这是一项有趣的任务。这是你用纯js的答案!

var peopleList = [];
var addButton = document.querySelector('button.add');
var submitButton = document.querySelector('button[type=submit]');
var debug = document.querySelector('pre.debug');
var mainForm = document.forms[0];
var ageFormField = mainForm.age;
var relationshipFormField = mainForm.rel;
var smokerFormField = mainForm.smoker;
var positionFormField=mainForm.position;

//Taken from https://www.inventpartners.com/open-source/free-web-software/javascript_is_int
function is_int(value) 
    if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) 
        return true;
     else 
        return false;
    


function formIsValid() 
    return ageFormField.value != '' && is_int(ageFormField.value) && relationshipFormField.selectedIndex != 0 && positionFormField.value !='';


function updateDebug() 
    if (peopleList.length != 0) 
        debug.innerText = JSON.stringify(peopleList);
        debug.setAttribute('style', 'display: block');
        submitButton.disabled = false;
     else 
        debug.innerText = '';
        debug.removeAttribute('style');
        submitButton.disabled = true;
    


function addEventClick(event) 
    event.preventDefault();
    if (formIsValid()) 
        peopleList.push(
            'age': ageFormField.value,
            'position':positionFormField.value,
            'relationship': relationshipFormField.options[relationshipFormField.selectedIndex].value,
            'isSmoker': smokerFormField.checked,
           
        );
        updateDebug();
        ageFormField.value = '';
        positionFormField.value='';
        relationshipFormField.selectedIndex = 0;
        smokerFormField.checked = false;
      
     else 
        var errors = '';
        if (ageFormField.value == '') 
            errors += 'Please enter your age!';
         else if (!is_int(ageFormField.value)) 
            errors += 'Age must be a numeric value!';
        
        if (relationshipFormField.selectedIndex == 0) 
            if (errors != '') 
                errors += '\n';
            
            errors += 'Please select your relationship status!';
        

        if (positionFormField.value == '') 
            if (errors != '') 
                errors += '\n';
            
            errors += 'Please enter your position!';
        
        if (errors != '') 
            alert(errors);
            errors = '';
        
         else if (
            errors != '') 
                alert(errors);
                errors = '';
        
    


function submitEventClick(event) 
    event.preventDefault();
    if (peopleList.length != 0) 
        var http = new XMLHttpRequest();
        var url = "savePeopleList.php";
        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        http.onreadystatechange = function() 
            if (http.readyState == 4) 
                if (http.status == 200) 
                    peopleList = [];
                    updateDebug();
                    alert('All of the changes were saved to the server!');
                 else 
                    alert('An error occured while sending the data to the server!');
                
            
        ;
        http.send(JSON.stringify(peopleList));
    


addButton.addEventListener('click', addEventClick, false);
submitButton.addEventListener('click', submitEventClick, false);
updateDebug();
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Household builder</title>
        <style>
            .debug 
                font-family: monospace;
                border: 1px solid black;
                padding: 10px;
                display: none;
            
        </style>
    </head>
    <body>
        <h1>Household builder</h1>
        <div class="builder">
            <ol class="household"></ol>
            <form>
                <div>
                    <label>Age
                        <input type="text" name="age">
                    </label>
                </div>
                <div>
                    <label>Position
                        <input type="text" name="position">
                    </label>
                </div>
                <div>
                    <label>Relationship
                        <select name="rel">
                            <option value="">---</option>
                            <option value="self">Self</option>
                            <option value="spouse">Spouse</option>
                            <option value="child">Child</option>
                            <option value="parent">Parent</option>
                            <option value="grandparent">Grandparent</option>
                            <option value="other">Other</option>
                        </select>
                    </label>
                </div>
                <div>
                    <label>Smoker?
                        <input type="checkbox" name="smoker">
                    </label>
                </div>
                <div>
                    <button class="add">add</button>
                </div>
                <div>
                    <button type="submit">submit</button>
                </div>
            </form>
        </div>
        <pre class="debug"></pre>
        <script type="text/javascript" src="./index.js"></script>
    </body>
</html>

【讨论】:

【参考方案3】:

遍历表单,获取各种元素并为每个元素创建新对象,然后为每个对象设置属性并推送到最终数组,这样可以很容易地解决您的问题。

然后您可以简单地使用querySelectorAll 匹配.debug 并使用JSON.stringify() 将您的数组转换为字符串并使用innerText 设置内容。

例子:

function go() 
  var debug_class = document.querySelectorAll(".debug");
  for (var i = 0; i < debug_class.length; i++) 
    var element = debug_class[i];
    element.innerText = JSON.stringify(serializeArray(document.querySelector("form")));
  



function serializeArray(form) 
  var field, l, s = [];
  if (typeof form == 'object' && form.nodeName == "FORM") 
    var len = form.elements.length;
    for (i = 0; i < len; i++) 
      field = form.elements[i];
      if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') 
        if (field.type == 'select-multiple') 
          l = form.elements[i].options.length;
          for (j = 0; j < l; j++) 
            if (field.options[j].selected)
              s[s.length] = 
                name: field.name,
                value: field.options[j].value
              ;
          
         else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) 
          s[s.length] = 
            name: field.name,
            value: field.value
          ;
        
      
    
  
  return s;
<form id="blah">
  <input type="text" name="input1" value="a"></input>
  <input type="text" name="input2" value="b"></input>
  <input type="text" name="input3" value="c"></input>
  <input type="text" name="input4" value="d"></input>

</form>
<button onclick="go()">Serialize!</button>

<div class="debug"></div>

编辑

在您的特定情况下,包含上述代码后,您必须在某些时候调用 go() 来生成序列化数据。

点击add后的操作如下

 document.querySelector(".add").onclick = function(event) 
        go();   // display in .debug
        event.preventDefault();
        createinput()
    

完整片段

function go() 
  var debug_class = document.querySelectorAll(".debug");
  for (var i = 0; i < debug_class.length; i++) 
    var element = debug_class[i];
    element.innerText = JSON.stringify(serializeArray(document.querySelector("form")));
  



function serializeArray(form) 
  var field, l, s = [];
  if (typeof form == 'object' && form.nodeName == "FORM") 
    var len = form.elements.length;
    for (i = 0; i < len; i++) 
      field = form.elements[i];
      if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') 
        if (field.type == 'select-multiple') 
          l = form.elements[i].options.length;
          for (j = 0; j < l; j++) 
            if (field.options[j].selected)
              s[s.length] = 
                name: field.name,
                value: field.options[j].value
              ;
          
         else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) 
          s[s.length] = 
            name: field.name,
            value: field.value
          ;
        
      
    
  
  return s;



function validate(form) 
  fail = validateAge(form.age.value)
  fail += validateRel(form.rel.value)

  if (fail == "") return true
  else 
    alert(fail);
    return false
  
  go();


function validateAge(field) 
  if (isNaN(field)) return "No age was entered. \n"
  else if (field < 1 || field > 200)
    return "Age must be greater than 0. \n"
  return ""


function validateRel(field) 
  if (field == "") return "Please select a relationship \n"
  return ""


document.querySelector("form").onsubmit = function() 
  return validate(this)


document.querySelector(".add").onclick = function(event) 
  go();
  event.preventDefault();
  createinput()


count = 0;

function createinput() 
  field_area = document.querySelector('.household')
  var li = document.createElement("li");
  var p1 = document.createElement("p");
  var p2 = document.createElement("p");
  var p3 = document.createElement("p");
  var x = document.getElementsByName("age")[0].value;
  var y = document.getElementsByName("rel")[0].value;
  var z = document.getElementsByName("smoker")[0].checked;
  if (!z) 
    z = "Non smoker \n";
   else 
    z = "Smoker \n";
  
  p1.innerHTML = x;
  p2.innerHTML = y;
  p3.innerHTML = z;
  li.appendChild(p1);
  li.appendChild(p2);
  li.appendChild(p3);
  field_area.appendChild(li);
  //removal link
  var removalLink = document.createElement('a');
  removalLink.onclick = function() 
    this.parentNode.parentNode.removeChild(this.parentNode)
  
  var removalText = document.createTextNode('Remove Field');
  removalLink.appendChild(removalText);
  li.appendChild(removalLink);
  count++


// serialize form

var data = ;
var inputs = [].slice.call(e.target.querySelector('form'));
inputs.forEach(input => 
  data[input.name] = input.value;
);
<ol class="household"></ol>
<form>
  <div>
    <label>Age
      <input type="text" name="age">
    </label>
  </div>
  <div>
    <label>Relationship
      <select name="rel">
        <option value="">---</option>
        <option value="self">Self</option>
        <option value="spouse">Spouse</option>
        <option value="child">Child</option>
        <option value="parent">Parent</option>
        <option value="grandparent">Grandparent</option>
        <option value="other">Other</option>
      </select>
    </label>
  </div>

  <div>

    <label>Smoker?
      <input type="checkbox" name="smoker">
    </label>
  </div>

  <div>
    <button class="add">add</button>
  </div>
  <div>
    <button type="submit">submit</button>
  </div>
</form>
</div>
<pre class="debug"></pre>

【讨论】:

嘿@mike510a 感谢分享。我添加了代码,但没有看到 class="debug" 中填充的值。我做错了什么? 在我的示例中,表单的名称是“blah”——对于您的情况,它将是 element.innerText = JSON.stringify(serializeArray(document.querySelector('form'))); 您还必须添加&lt;button onclick="go()"&gt;Serialize!&lt;/button&gt; 部分才能使其实际工作——特别是onlick="go()" 部分 嘿 Mike - 我无法添加任何额外的 HTML。对此只有纯 JS。 :// 嘿@mike510a 我仍然没有在 class="debug" 中看到 JSON 值。 ://

以上是关于HTML/Javascript 表单 如何将表单数据序列化为 JSON 并在类中显示?的主要内容,如果未能解决你的问题,请参考以下文章

如何将数组作为表单数据传递给 Postman

如何将表单 FormSeetController 中的数据传递给 ViewController?

从表单发送电子邮件(仅 HTML、javascript)

在同一视图中使用多个模型时将表单数据传递给模型

基于 HTML/JavaScript 中的用户选择动态删除表单元素

Django 频道:将表单数据传递给消费者