如何将数据从csv文件加载到表单字段?

时间:2019-06-15 09:32:17

标签: javascript jquery html ajax

我正在尝试将HTML表单与csv文件链接以自动填充表单字段。根据用户在第一个字段中选择的内容,应使用适当的值自动填充第二个字段。当用户开始在第一个字段中输入内容时,输入字段会自动从csv文件中提取数据以显示可用选项。用户在该字段中填写3个单词后,将显示选项。

此外,为了避免代码中出现任何CORS问题,我在CSV文件URL中添加了其他URL,这使得任何Web应用程序都可以访问它。

我可以借助网上提供的示例来编写此代码。但是,我的代码无法正常工作。我试图自己解决这个问题。但是我对编码不够了解。

任何人都可以帮我解决这个问题。

<script>
$(function() { function processData(allText) { var record_num = 2; 
// or however many elements there are in each row 
var allTextLines = allText.split(/\r\n|\n/); var lines = []; var headings = allTextLines.shift().split(','); while (allTextLines.length > 0) { var tobj = {}, entry; entry = allTextLines.shift().split(','); tobj['label'] = entry[0]; tobj['value'] = entry[1]; lines.push(tobj); } return lines; } 

// Storage for lists of CSV Data

 var lists = []; 

// Get the CSV Content
 $.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/file.txt  ", function(data) { lists = processData(data); }); $("#species").autocomplete({ minLength: 3, source: lists, select: function(event, ui) { $("#species").val(ui.item.label); $("#identifiant").val(ui.item.value); return false; } }); });)
</script>
 <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
         
  <form> 
  <div class="ui-widget"> <label for="species">Species: </label> <input id="species"> <label for="identifiant">Identifiant: </label> <input id="identifiant" style="width: 6em;"> </div></form>

2 个答案:

答案 0 :(得分:0)

我的解决方案是一种自动完成-称为预输入。

我显示了过滤后的列表,所以您可以看到正在发生的事情,但是您可以将其放置在任何地方-例如,在输入字段下方的下拉列表中。

$(function() {
  // processing CSV data
  function processData(allText) {

    // splitting lines
    var allTextLines = allText.split(/\r\n|\n/);

    const speciesData = []
    // reading data into array, if it's not the first row (CSV header) AND
    // if it's not 'Species'
    let j = 0; // this will be the item's index
    for (let i = 0; i < allTextLines.length - 1; i++) {
      if (i !== 0 && allTextLines[i] !== 'Species') {
        const record = allTextLines[i].split(',')
        speciesData.push({
          label: record[0],
          value: record[1].trim(), // it has a lot of whitespace
          index: j // adding this, so we can keep track of items
        })
        j++; // incrementing index
      }
    }

    // returning processed data
    return speciesData;
  }

  // Storage for lists of processed CSV Data
  let lists = [];

  // Get the CSV Content
  $.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/file.txt  ", function(data) {
    // making processed data availabel app-wide
    lists = processData(data);
    // filling the 'suggestions list' the first time
    suggestionListHtml(lists, $('.suggestions-container'))
  });

  // actions on input field input event
  // only the third param differs in filterSpecies()
  $('#species').on('input', function(e) {
    const filteredList = filterSpecies($(this).val(), lists, 'label')
    suggestionListHtml(filteredList, $('.suggestions-container'))
  })
  $('#identifiant').on('input', function(e) {
    const filteredList = filterSpecies($(this).val(), lists, 'value')
    suggestionListHtml(filteredList, $('.suggestions-container'))
  })

  // clicking on an item in the 'suggestions list' fills out the input fields
  $('.suggestions-container').on('click', '.suggestion', function(e) {
    const item = lists[$(this).attr('data-listindex')]
    $('#species').val(item.label)
    $('#identifiant').val(item.value)
  })

});

function suggestionListHtml(filteredList, container) {
  // creating HTML template for the 'suggestions list'
  let html = ''
  filteredList.forEach(item => {
    html += `<span class="suggestion" data-listindex="${item.index}">label: ${item.label} - value: ${item.value}</span>`
  })

  // modifying the displayed 'suggestions list'
  container
    .empty()
    .append(html)
}

// filtering the processed list
// @param substr - the text from the input field
// @param list - the list to be filtered
// @param attr - one of the keys in the processed list (label or value)
function filterSpecies(substr, list, attr) {
  // doing the actual filtering
  const filteredList = list.filter(item => {
    return item[attr].toLowerCase().includes(substr.toLowerCase())
  })
  return filteredList
}
.suggestions-container span {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <div class="ui-widget">
    <label for="species">Species: </label>
    <input id="species">
    <label for="identifiant">Identifiant: </label>
    <input id="identifiant" style="width: 6em;">
  </div>
  <div class="suggestions-container">

  </div>
</form>

答案 1 :(得分:0)

这是修改后的答案,可以使用jquery-ui自动完成功能。

解决方案:$.get()异步函数(数据在页面加载时不易获得),因此jquery-ui自动完成功能不适用于更新后的{{1 }}数组,因为它(似乎如此)不适用于动态生成的数据。因此,必须使用lists[]的回调函数中新到达的数据来刷新自动完成的

$.get()-这是关键行,因为它会使用新数据更新自动填充的源。

$("#species").autocomplete('option', 'source', lists)
// Only needed for working example
var myCSV = "Species,Identifiant\r\n";
myCSV += "Species A,320439\r\n";
myCSV += "Species B,349450\r\n";
myCSV += "Species C,43435904\r\n";
myCSV += "Species D,320440\r\n";
myCSV += "Species E,349451\r\n";
myCSV += "Species F,43435905\r\n";
console.log(myCSV);

// Begin jQuery Code
$(function() {
  function processData(allText) {
    // var record_num = 2; // or however many elements there are in each row
    var allTextLines = allText.split(/\r\n|\n/);
    var lines = [];
    var headings = allTextLines.shift().split(',');
    while (allTextLines.length > 0) {
      var tobj = {},
        entry;
      entry = allTextLines.shift().split(',');
      /*
      Normally we'd read the headers into the object.
      Since we will be using Autocomplete, it's looking for an array of objects with 'label' and 'value' properties.
      tobj[headings[0]] = entry[0];
      tobj[headings[1]] = entry[1];
      */
      if (typeof entry[1] !== 'undefined') {
        let prefix = !entry[0].includes('Species') ? 'Species ' : ''
        tobj['label'] = prefix + entry[0];
        tobj['value'] = entry[1].trim();
        lines.push(tobj);
      }
    }
    return lines;
  }
  let lists = [];

  // For working example 
  // lists = processData(myCSV);
  // console.log('lists1', lists)

  // In your script you will get this content from the CSV File
  // Get the CSV Content
  $.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/file.txt", function(data) {
    lists = processData(data);
    $("#species").autocomplete('option', 'source', lists)
    console.log('lists2', lists)
  });

  $("#species").autocomplete({
    minLength: 3,
    source: lists,
    focus: function(event, ui) {
      console.log(ui)
      $("#species").val(ui.item.label);
      return false;
    },
    select: function(event, ui) {
      $("#species").val(ui.item.label);
      $("#identifiant").val(ui.item.value);
      return false;
    }
  });
});

processData()函数无法与您提供的源一起正常工作,因此也必须对其进行修改。