序列化表单数据返回未定义

时间:2019-07-18 13:17:10

标签: javascript jquery html json

我正在尝试从JSON API填充动态列表,我需要序列化表单数据,然后使用它触发AJAX请求,但它返回未定义的内容。

var s_name = '';

$(document).ready(function() {
  var url1 = "https://script.google.com/macros/s/AKfycbx91EB9aIOXRYNmP108ZcPuEGgUqZWZli0KWdj5A3Ts0Qc6hrc/exec";

  $.getJSON(url1, function(data) {
    $.each(data, function(index, value) {
      var $option = $('<option value="' + value.ID + '">' + value.Client + '</option>');
      $option.text();
      // APPEND OR INSERT DATA TO SELECT ELEMENT.
      $('#clist').append($option);
    });
  });
});

$(document).ready(function() {
  $("button").click(function() {
    $("div").text($("form").serialize());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <label for="clist">Select Client Name</label>
  <select class="form-control" id="clist" name="clist" style="width:100%">
    <option value="">-- Select --</option>
  </select>
</form>

<button>Test</button>
<div></div>

1 个答案:

答案 0 :(得分:1)

您执行的代码有效,问题在于您的退货仅带来客户的姓名而不是其客户身份

var s_name = '';

$(document).ready(function() {
  var url1 = "https://script.google.com/macros/s/AKfycbx91EB9aIOXRYNmP108ZcPuEGgUqZWZli0KWdj5A3Ts0Qc6hrc/exec";

  $.getJSON(url1, function(data) {
    $.each(data, function(index, value) {
      var $option = $('<option value="' + value.Client + '">' + value.Client + '</option>');
      $option.text();
      // APPEND OR INSERT DATA TO SELECT ELEMENT.
      $('#clist').append($option);
    });
  });
});

$(document).ready(function() {
  $("button").click(function() {
    $("div").text($("form").serialize());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <label for="clist">Select Client Name</label>
  <select class="form-control" id="clist" name="clist" style="width:100%">
    <option value="">-- Select --</option>
  </select>
</form>

<button>Test</button>
<div></div>