获取数组中所有选中的复选框到 POST 到 API

Getting all selected checkboxes in an array to POST to API

我想通过 urlencoded.append

将数组中所有选中的复选框获取到 POST 到 API

urlencoded.append("typeID", (document.getElementById("type").value==1?"1":document.getElementById("type").value==2?"2":"3"));
<div id="myDiv">
  <input type="checkbox" name="name" value="1" id="type-id">
  <label>Food Deals</label>
  <br>
  <input type="checkbox" name="name" value="2" id="type-id">
  <label>Groceries Deals</label>
  <br>
  <input type="checkbox" name="name" value="3" id="type-id">
  <label>Karam Box</label>
  <br>
</div>

一些注意事项:

  1. HTML(和现实)中,id 是唯一的。
  2. JS 中选中的复选框是 checked 而不是 selected

为了收集所有选中的值,您可以这样做:

function demo() {
  document.querySelectorAll('input:checked').forEach(element => {
    console.log(element.value);
  });  
}
<div>  
  <label>1<input type="checkbox" value="1" /></label>
  <label>2<input type="checkbox" value="2" /></label>  
  <label>3<input type="checkbox" value="3" / ></label>
  <label>4<input type="checkbox" value="4" /></label>
  <label>5<input type="checkbox" value="5" /></label>  
  <label>6<input type="checkbox" value="6" / ></label>
</div>
<button type="button" onclick="demo()">"POST"</button>

前置编辑

在 OP 的示例代码中被称为 urlencoded.

因此,为了快速修复 OP 的代码,解决方案可能如下所示...

// make an array from the ...
Array.from(
  // ... node list of every checked
  // ckeckbox control withing the #myDiv element ...
  document.querySelectorAll('#myDiv [type="checkbox"]:checked')
)
.reduce((formData, control) => {

  // ... and append key/name and value to `formData` ...
  formData.append(control.name, control.value);
  return formData;

  // ... which is represented by the `urlencoded` object
  // that got provided as the `reduce` task's initial value.
}, urlencoded);

下面是一个完整且有效的示例代码,用于研究 XHR and FormData.

的使用

+++编辑结束+++

除了日志记录之外,还要检查您的 DevTools Network 选项卡。应该能够检查对 https://stacksnippets.net/ 的失败 (404) POST 请求,但具有正确发送的表单数据。

所提供的方法使用表单元素,它拦截并阻止浏览器的表单提交,但从表单的 method and action 值创建自己的 XHR。

为了collect/aggregate表单数据,它使用FormData Web API. Such an object can be directly passed to the XHR's send方法。

function createXHRFromForm(form) {
  const xhr = new XMLHttpRequest;

  xhr.open(
    form.method,
    form.action,
    true
  );
  xhr.setRequestHeader(
    'Content-Type',
    'application/x-www-form-urlencoded'
  );
  // xhr.onreadystatechange = function() {
  //   if (
  //     (this.readyState === XMLHttpRequest.DONE)
  //     && (this.status === 200)
  //   ) {
  //     // handle success
  //   }
  // };
  return xhr;
}
function createCheckboxFormData(form) {
  // for the given example form
  // following line already was sufficient enough
  //
  // return new FormData(form);
  //
  // but a custom aggregation is supposed to be shown.
  return Array
    .from(
      form.querySelectorAll('[type="checkbox"]:checked')
    )
    .reduce((formData, control) => {

      formData.append(control.name, control.value);
      return formData;

    }, new FormData); 
}

function handleCheckboxDataSubmit(evt) {
  evt.preventDefault();
  
  const form = evt.currentTarget;

  const xhr = createXHRFromForm(form);
  const formData = createCheckboxFormData(form);

  console.clear();
  console.log({
    entries: [...formData.entries()],
    name: formData.getAll('name'),
  });
  xhr.send(formData);

  return false;
}

function main() {
  document
    .querySelector('form[name="myForm"]')
    .addEventListener('submit', handleCheckboxDataSubmit);
}
main();
:not([type="submit"]) {
  margin: 0!important;
  padding: 0!important;
}
body { zoom: .85; }
label { display: block; cursor: pointer; }
[type="submit"] { margin-top: 3px; }
<form name="myForm" action="/" method="post">
  <label>
    <input type="checkbox" name="name" value="1" checked/>
    <span class="label">Food Deals</span>
  </label>
  <label>
    <input type="checkbox" name="name" value="2" checked/>
    <span class="label">Groceries Deals</span>
  </label>
  <label>
    <input type="checkbox" name="name" value="3"/>
    <span class="label">Karam Box</span>
  </label>
  <button type="submit">POST</button>
</form>