为什么在循环中多次显示数据?

时间:2019-07-05 15:59:09

标签: javascript jquery html ajax

我一直在尝试建立一种连接到API的搜索引擎。它接受用户输入并从API返回信息。将来应该会有“动态”数量的输入字段,但是目前我正在使用五个固定数量的字段。循环将使用一定数量的字段,并使用该输入来调用该数量的API。

我尝试在循环中放置一个常量(即5),但有趣的部分是,当然3会调用应用3次,但会输出6个字段,而2会调用API 2次,但会输出3个行,因此似乎它没有遵循循环,而是遵循其他规则。同时,在控制台中(带有日志),我可以看到仅在循环定义的时间正确调用了API,因此我相信在$.getJSON级别出现了问题

问题是最后创建的表具有15行,而不是预期的5行(每个输入一行)。为什么您认为这种情况正在发生?

预先感谢

<form name="inputform" method="get" width="50">
  <input type="text" name="field0" id="field0" size="50">
  <input type="text" name="field1" id="field1" size="50">
  <input type="text" name="field2" id="field2" size="50">
  <input type="text" name="field3" id="field3" size="50">
  <input type="text" name="field4" id="field4" size="50">
</form>

<table id="table">
  <tr>
    <th>id</th>
    <th>Name</th>
    <th>Age</th>
    <th>Preference</th>
  </tr>
</table>

<input id="getInfo" type="button" value="Submit" /><br/>
var customURL = "http://apitest.com/test/";
var customURL1 = '';

$('#getInfo').click(function() {
  $('#table tr').not(':first').remove();
  var fields = document.getElementsByTagName('input');
  var table = document.getElementById('table');

  if (localStorage.myJSON !== undefined) {
    var myJSON = JSON.parse(localStorage.myJSON);
  }
  var html = '';
  for (var i = 0; i < elements.length - 1; i++) {
    customURL1 = customURL + document.getElementById('field' + i + '').value;
    console.log(customURL1);

    $.getJSON(customURL1, function(data) {
          console.log(data);
          html += '<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>';
          $('#table tr').first().after(html);

1 个答案:

答案 0 :(得分:0)

每次获得AJAX响应时,您都将响应附加到html变量中,然后将其添加到表的第一行之后。由于html变量已经包含先前响应的结果,并且已经将它们插入表中,因此您将获得重复项。

只需将新行直接插入表中,而不是将新行连接到html

$.getJSON(customURL1, function(data) {
      console.log(data);
      $('#table tr').first().after('<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>');