簡體   English   中英

使用nodeJS創建依賴下拉菜單過濾器

[英]Creating dependent dropdown menu filter using nodeJS

我需要在網頁上創建兩個下拉菜單 - (第二個下拉菜單取決於第一個下拉菜單) - 並使用來自 a.csv 文件的兩個不同列的記錄填充這兩個菜單。

我可以使用 NodeJS 讀取 csv 文件,並將所需的列放入兩個不同的 arrays 中,如下所示:

uniqueCountryName
[
 'Italy',
 'Spain',
 'France',
 'England'
]
uniqueCityName
[
 'Paris',
 'Milan',
 'Marseilles',
 'Venice'
 'London',
 'Rome',
 'Berlin',
 'Madrid',
 'Barcelona' 
]

這是我到目前為止使用的 nodeJS 代碼:

const csv = require('csv-parser');
const fs = require('fs');
const results = [];
const CountryName = [];
const CityName = [];

fs.createReadStream('C:/Users/learningsql/Desktop/project.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
    var CountryName = []
    for (var item in results) {
        CountryName.push(results[item]["CountryName"])
    }
    /* console.log(CountryName) */

    const uniqueCountryName = Array.from(new Set(CountryName));
    console.log("uniqueCountryName")
    console.log(uniqueCountryName)
});

fs.createReadStream('C:/Users/learningsql/Desktop/project.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
    for (var item in results) {
        CityName.push(results[item]["CityName"])
    }
    /* console.log(CityName) */

    const uniqueCityName = Array.from(new Set(CityName));
    console.log("uniqueCityName")
    console.log(uniqueCityName)
});

現在我需要做兩件事:首先,我需要在網頁上的兩個不同下拉菜單中填充這兩個不同的 arrays。 CountryName 應該 go 進入第一個下拉菜單, CityName 應該 go 進入第二個下拉菜單。 據我了解,瀏覽器無法從終端讀取output,所以需要使用Express.JS搭建服務器。 我怎樣才能做到這一點?

其次,正如我已經提到的,第二個下拉記錄應該依賴於第一個,我們如何映射/鏈接 arrays? 例如,當 I select Italy 在第一個下拉菜單中時,只有意大利城市(米蘭、威尼斯、羅馬等)應該出現在第二個下拉菜單中。 如果我 select 西班牙,則只有西班牙城市應顯示在下拉菜單中(馬德里、巴塞羅那等)。

作為參考,下拉菜單應該是這樣的

我是 NodeJS 的新手,任何幫助都將不勝感激。 謝謝。

你在這里問了兩個問題。 一是如何使用快遞。 另一個是如何實現依賴下拉。 也許這應該是兩個不同的問題,但讓我在這里解決每個問題。 一、我們如何使用express(這是一個用node寫的web服務器)

一、如何使用快遞

  1. 將 express 安裝在您選擇的目錄中(有關詳細信息,請參閱鏈接)
  2. $ npm install express --save
  3. 新建 javascript 文件
  4. 使用下面的代碼
    var express = require('express');
    var app = express();   
    app.get('/', function (req, res) {
      res.send("<h1>hello world</h1>");
    });    
    app.listen(8080, function () {
      console.log('Example app listening on port 8080!');
      //call this app from localhost://8080 
    });

這是一個簡單的“hello world”。 我已在此博客中詳細解釋了這一點。 如果要使用 html 文件而不是簡單的 html 代碼,請使用以下代碼:

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('index.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

請注意,您需要使用 npm 或其他 package 來安裝 express、http 和 fs。 您的 html 代碼將在index.html中。

您的第二個問題是關於如何使用依賴下拉菜單。

2. 依賴下拉菜單

對於依賴下拉列表,您純粹在客戶端工作。 所以普通的 javascript 代碼可以工作。 例如,您可以使用 jquery 或其他有用的庫。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<!-- optionally if you need translation for your language then include locale file as mentioned below -->
<script src="path/to/js/locales/<lang>.js"></script>
<h1>Dependent Dropdown</h1>

<form name="myform" id="myForm">
    <select name="optone" id="continentSel" size="1">
        <option value="" selected="selected">Select continent</option>
    </select>
    <br>
    <br>
    <select name="opttwo" id="countrySel" size="1">
        <option value="" selected="selected">Please select continent first</option>
    </select>
    <br>
    <br>
    <select name="optthree" id="citySel" size="1">
        <option value="" selected="selected">Please select state first </option>
    </select>
</form>
<hr/>


<script>
var stateObject = {
  "Europe": {
          "France": ["Paris", "Lyon"],
          "UK": ["London", "Birmingham"]
      },
      "Africa": {
          "Senegal": ["Dakar", "Louga"],
          "South Africa": ["Cape Town", "Pretoria"]
      }
}
window.onload = function () {
    var continentSel = document.getElementById("continentSel"),
        countrySel = document.getElementById("countrySel"),
        citySel = document.getElementById("citySel");
    for (var item in stateObject) {
        continentSel.options[continentSel.options.length] = new Option(item, item);
    }
    continentSel.onchange = function () {
        countrySel.length = 1; // remove all options bar first
        citySel.length = 1; // remove all options bar first
        if (this.selectedIndex < 1) return; // done
        for (var item in stateObject[this.value]) {
            countrySel.options[countrySel.options.length] = new Option(item, item);
        }
    }
    continentSel.onchange(); // reset in case page is reloaded
    countrySel.onchange = function () {
        citySel.length = 1; // remove all options bar first
        if (this.selectedIndex < 1) return; // done
        var cities = stateObject[continentSel.value][this.value];
        for (var i = 0; i < cities.length; i++) {
            citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
        }
    }
}
</script>

最后在這里查看完整的工作代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM