如何将空数组附加到 FormData 对象?

Dog*_*las 7 javascript php ajax form-data

我有以下问题:

一个 html 表单,在 FormData 上使用 N 个复选框,通过 ajax 发送请求及其信息。在 PHP 上,$_POST['teste'] 变量不存在...

<form id="teste_form">
    <input type="checkbox" name="teste[]">
    <input type="checkbox" name="teste[]">
    <input type="checkbox" name="teste[]">
    <input type="checkbox" name="teste[]">...
</form>

<script>
    var form_data_obj = new FormData( document.getElementById('teste_form') );
    $.ajax({
        ...
        data: form_data_obj
        ...
    });
</script>
Run Code Online (Sandbox Code Playgroud)

我知道我可以在 PHP 上使用“if(isset(...))”,但我真的不喜欢这个解决方案。对我来说,最好的解决方案是从 FormData 对象向 PHP 发送一个空数组。

Obs:我尝试过类似的方法:

  • form_data_obj.append('teste[]',未定义)。
  • form_data_obj.append('teste[]', 0).

但没有成功... PHP 上的结果分别是: ["undefined"], ["0"]

我想在 PHP 中获取 $_POST ['test'] = []

那可能吗?

Tah*_*ksu 3

听起来像这样:How to Submit empty array from HTML Form Post to PHP

解决方法:您可以在客户端使用带有空值的隐藏输入元素,并在服务器端使用空值检查。像这样的事情:

var appended = null;
$('.confirm_appointment').submit(function(e) {

  if (appended !== null) appended.remove();
  /************************************/
  if ($("input[name='teste[]']:checked").length == 0) {
    appended = $("<input type='hidden' name='teste[]' value=''>").appendTo($(this));
  }
  /************************************/

  e.preventDefault();
  $(this).append(decodeURIComponent($(this).serialize()) + '<br />');
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name='confirm_appointment' method='post' class='confirm_appointment'>
  <input type='checkbox' name="teste[]" value='hello1' />
  <input type='checkbox' name="teste[]" value='hello2' />
  <input type='checkbox' name="teste[]" value='hello3' />
  <input type='checkbox' name="teste[]" value='hello4' />
  <input type='submit' class='update_appointment_button' value='submit' /><br />
</form>
Run Code Online (Sandbox Code Playgroud)

在 PHP 方面:

$teste = array_filter($_POST["teste"]);
Run Code Online (Sandbox Code Playgroud)