为隐藏的输入标签添加值并提交到表单

Adding value to hidden input tag and submitting to form

我有一个显示我的 POST 数据的测试页面。我正在尝试查看我刚刚提交的 post,但看不到我在表单中添加的 payload

HTML:

  <form id="test-form" action="/test/" method="post"> {# pass data to /test/ URL #}
    <div class="test-button-set">
      <button type="button" id="hdfs-test" class="btn btn-default btn-lg selected">HDFS</button>
      <button type="button" id="hive-test" class="btn btn-default btn-lg">HIVE</button>
      <button type="button" id="hdfs-hive-test" class="btn btn-default btn-lg">BOTH</button>
    </div>
    <button id="submit-test" type="submit" class="btn btn-default btn-lg">Submit</button>
    <input type="hidden" id="payload">
  </form>

JS:

var testData = {
        "timestamp": "",
        "hive": 0,
        "hdfs": 0,
        "beacons":[]
    };

var testRun = document.getElementById("test-form");
    testRun.addEventListener('submit', function(event) {
        event.preventDefault();
        testData["timestamp"] = new Date().getTime();
        console.log(testData);
        var payload = document.getElementById("payload");
        payload.value = testData;
        $(this).trigger('submit', true);
    });

目前,我看不到我给 <input type="hidden" id="payload"> 的值,这让我相信它没有得到 posted。

您需要为隐藏标签添加名称属性。

名称就是您所指的名称。

<input type="hidden" name="payload" id="payload">

您需要为输入命名:

<input type="hidden" id="payload" name="payload">

看到这个 SO 答案:Difference between id and name attributes in HTML