即使没有选中复选框,也要定义数组

时间:2018-05-24 19:38:52

标签: javascript jquery html

我有以下HTML:

<form id="download">
  <label>
    <input name="docs" id="doc1" value="doc1" type="checkbox">File 1
  </label>          
  <label>
    <input name="docs" id="doc2" value="doc2" type="checkbox">File 2
  </label>          
  <button class="button" type="submit">Download</button>            
</form>

以下JQuery:

$(function () {

  $("#download").on("submit", function (event) {

    event.preventDefault();

    var $form = $(this);

    console.log($form.serializeToJSON());

    $.ajax({
      url: "/download",
      data: JSON.stringify($form.serializeToJSON()),
      dataType: "json",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      type: "post"
    })
    .done(function (data, status, xhr) { })
    .fail(function (xhr, status, error) { });

  });
});

当我选中两个复选框时,我在控制台上得到以下内容:

Object { names: [ "doc1", "doc2" ] }

如果我只选择一个复选框,我会:

Object { names: "doc1" }

我需要&#34;姓名&#34;总是一个阵列,因为后端期待它。

所以,如果我只选择一个,我会得到:

Object { names: [ "doc1" ] }

如果我没有选中任何复选框,那么:

Object { names: [] }

解决这个问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

只需在代码中添加一张支票:

x = 100000
while x < 100000:
y = x + 100000
z =  (3*10000)-1/(10-3)
    if y != z:
    x += 1
else: 
print(x)