如何将HTML表单(JSON格式)中的数据分配给变量?

时间:2016-05-04 11:17:56

标签: javascript html json

在我的abc.html中,我有以下代码将表格数据(现在硬编码)转换为JSON格式:

    <body>
    <form enctype='application/json' method="POST" name="myForm">

    <p><label>Company:</label>
    <input name='Company' value='TESTCOMPANY'> </p>

    <p><label>User Id:</label>
    <input name='User' value='TESTUSER'></p>

    <p><label>Division:</label>
    <input type="text" name='parameterMap[p1]' value='12345' ></p>

    <p><label>From:</label>
    <input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>

    <p><label>To:</label>
    <input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>

    <input value="Submit" type="submit" onclick="submitform()">
    </form>
    </body>

从上面的代码我得到*

{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}*

现在我需要将由此数据形成的Json String分配给变量&#39; FormData&#39;所以FormData就像:

FormData = '{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}'

如何进行数据分配?

abc.html中的更多代码将以下列方式使用此变量FormData:

function sendAjax() {

    $.ajax({
        url : "myurl",
        type : 'POST',
        dataType : 'json',
        data : FormData,
        contentType : 'application/json',
        mimeType : 'application/json',
        success : function(data) {
            alert(data.uuid);
        },
        error : function(data, status, er) {
            alert("error: " + data + " status: " + status + " er:" + er);
        }
    });
    }

4 个答案:

答案 0 :(得分:0)

如果您未在后端处理此问题,则可以使用JSON.stringify()在变量中检索Javascript中的数据,然后将其作为JSON应用于您的数据。

这是一个有效的代码:

    function submitform() {
      var FormData = {
        Company: myForm.Company.value,
        User: myForm.User.value,
        parameterMap: {
          p1: myForm.p1.value,
          p2: myForm.p2.value,
          p3: myForm.p3.value
        }
      };
      console.log(FormData);

      $.ajax({
        url: "myurl",
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(FormData),
        contentType: 'application/json',
        mimeType: 'application/json',
        success: function(data) {
          alert(data.uuid);
        },
        error: function(data, status, er) {
          alert("error: " + data + " status: " + status + " er:" + er);
        }
      });
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype='application/json' method="POST" name="myForm">

  <p>
    <label>Company:</label>
    <input name='Company' value='TESTCOMPANY'>
  </p>

  <p>
    <label>User Id:</label>
    <input name='User' value='TESTUSER'>
  </p>

  <p>
    <label>Division:</label>
    <input type="text" name='p1' value='12345'>
  </p>

  <p>
    <label>From:</label>
    <input type="text" name='p2' value='20-MAR-2016'>
  </p>

  <p>
    <label>To:</label>
    <input type="text" name='p3' value='22-MAR-2016'>
  </p>

  <input value="Submit" type="submit" onclick="submitform()">
</form>

备注:

使用 Javascript naming conventions ,例如FormData最好是formData

答案 1 :(得分:0)

使用提供的HTML结构,您可以使用以下格式将数据转换为格式:

function submitform(){
    var form = document.querySelector('form');
    var result = {};
    var input = form.getElementsByTagName('input');
    for(var i = 0; i < input.length; i ++) {
        var row = input[i];
        var rowName = ((row.name || '').match(/(\w+)(\[(\w+)\])?/) || []);
        var rowIndex = rowName[3];
        rowName = rowName[1];
        if(rowName) {
            var typeOfRowIndex = typeof rowIndex;
            var rowValue = row.value;
            if(typeof result[rowName] === 'undefined') {
                var rowToAdd = {};
                rowToAdd[rowIndex] = rowValue;
                result[rowName] = typeOfRowIndex === 'undefined' ? rowValue : rowToAdd;
            } else if(typeOfRowIndex !== 'undefined') {
                result[rowName][rowIndex] = rowValue;
            }
        }
    }
    document.getElementById('output').innerHTML = JSON.stringify(result)
    console.log(result);
    return false;
}
<body>
  <form enctype='application/json' method="POST" name="myForm">

    <p>
      <label>Company:</label>
      <input name='Company' value='TESTCOMPANY'>
    </p>

    <p>
      <label>User Id:</label>
      <input name='User' value='TESTUSER'>
    </p>

    <p>
      <label>Division:</label>
      <input type="text" name='parameterMap[p1]' value='12345'>
    </p>

    <p>
      <label>From:</label>
      <input type="text" name='parameterMap[p2]' value='20-MAR-2016'>
    </p>

    <p>
      <label>To:</label>
      <input type="text" name='parameterMap[p3]' value='22-MAR-2016'>
    </p>

    <input value="Submit" type="submit" onclick="return submitform()">
  </form>
  <p>JSON Output (after clicking submit button):</p>
  <div id="output"></div>
  <p>Can also check console to see JSON object (after clicking submit button)</p>
</body>

答案 2 :(得分:-1)

True

答案 3 :(得分:-1)

我不喜欢jQuery,但是:

var $inputs = $('form[name="myForm"]').find('input');

var res = {};
Array.prototype.forEach.call($inputs, function($item, index) {
  res[ $item.getAttribute('name') ] = $item.value;
});

var FormData = JSON.stringify(res);

alert(FormData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <form enctype='application/json' method="POST" name="myForm">

    <p><label>Company:</label>
      <input name='Company' value='TESTCOMPANY'> </p>

    <p><label>User Id:</label>
      <input name='User' value='TESTUSER'></p>

    <p><label>Division:</label>
      <input type="text" name='parameterMap[p1]' value='12345' ></p>

    <p><label>From:</label>
      <input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>

    <p><label>To:</label>
      <input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>

    <input value="Submit" type="submit" onclick="submitform()">
  </form>
</body>