在使用JavaScript用单行位置的csv文件填充我的html下拉列表时遇到麻烦

sqyvllje  于 2023-07-31  发布在  Java
关注(0)|答案(1)|浏览(81)

我试图用一个csv文件填充我的html下拉菜单,该文件包含使用JavaScript的单行位置,但它不工作。有没有人能帮上忙?这里的问题是什么?locations.csv文件与此index.html文件位于同一文件夹中。
我已经删除了代码中不必要的部分,所以如果你发现任何语法错误,请忽略。代码运行正常,唯一的问题是无法重新填充位置。

const form = document.getElementById('prediction-form');
const resultDiv = document.getElementById('result');
const locationSelect = document.getElementById('location');

// Fetch locations from CSV file
fetch('locations.csv')
  .then(response => response.text())
  .then(csvData => {
    const rows = csvData.split('\n');
    for (let i = 1; i < rows.length; i++) {
      const location = rows[i].trim();
      if (location !== '') {
        const option = document.createElement('option');
        option.value = location;
        option.textContent = location;
        locationSelect.appendChild(option);
      }
    }
  })
  .catch(error => {
    console.error('Error fetching locations:', error);
  });

form.addEventListener('submit', function(event) {
  event.preventDefault();

  // Retrieve the form values
  const location = document.getElementById('location').value;
  const sqft = parseFloat(document.getElementById('sqft').value);
  const bath = parseFloat(document.getElementById('bath').value);
  const bhk = parseFloat(document.getElementById('bhk').value);
});

个字符
代码未按预期填充位置的html下拉列表。救命啊!救命啊!

lndjwyie

lndjwyie1#

当您删除fetch("location.csv")并将其替换为locations变量时,您可以看到您的逻辑正在工作,因此问题出在您的fetch()或数据上。如果这是你的fetch()的问题,你应该在控制台看到一些错误。很可能是HTTP状态码400 Not Found,但这只是猜测。在这种情况下,您应该检查文件是否确实存在于服务器上所需的位置/路径上,并相应地调整路径。
如果您的数据出错,例如该文件实际上不包含任何位置或不包含\n,那么您将看不到任何位置,因为您还有一个小错误:你的for循环从索引1开始,而不是0,所以第一个位置不会显示。当然,除非第一行是一个标题,在这种情况下,这一切都很好。
在这里,您的代码删除了fetch(),并添加了一个变量csvData,它模拟了您所期望的.csv文件。

const form = document.getElementById('prediction-form');
const resultDiv = document.getElementById('result');
const locationSelect = document.getElementById('location');

// Fetch locations from CSV file
const csvData = "Locations\nLoc1\nLoc2\nLoc3"
const rows = csvData.split('\n');
for (let i = 1; i < rows.length; i++) {
  const location = rows[i].trim();
  if (location !== '') {
    const option = document.createElement('option');
    option.value = location;
    option.textContent = location;
    locationSelect.appendChild(option);
  }
}

form.addEventListener('submit', function(event) {
  event.preventDefault();

  // Retrieve the form values
  const location = document.getElementById('location').value;
  const sqft = parseFloat(document.getElementById('sqft').value);
  const bath = parseFloat(document.getElementById('bath').value);
  const bhk = parseFloat(document.getElementById('bhk').value);
});

个字符

相关问题