简体   繁体   English

使用nodeJS创建依赖下拉菜单过滤器

[英]Creating dependent dropdown menu filter using nodeJS

I need to create two dropdown menus on a webpage - (the second dropdown menu is dependent on the first dropdown menu) - and populate both the menus with records from two different columns of a.csv file.我需要在网页上创建两个下拉菜单 - (第二个下拉菜单取决于第一个下拉菜单) - 并使用来自 a.csv 文件的两个不同列的记录填充这两个菜单。

I'm able to read the csv file using NodeJS and get both the required columns into two different arrays as below:我可以使用 NodeJS 读取 csv 文件,并将所需的列放入两个不同的 arrays 中,如下所示:

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

This is the nodeJS code I've used so far:这是我到目前为止使用的 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)
});

Now I need to do two things: First I need to populate these two different arrays in two different dropdown menus on a webpage.现在我需要做两件事:首先,我需要在网页上的两个不同下拉菜单中填充这两个不同的 arrays。 The CountryName should go into the first dropdown menu and the CityName should go into the second dropdown menu. CountryName 应该 go 进入第一个下拉菜单, CityName 应该 go 进入第二个下拉菜单。 It's my understanding that browser can't read the output from the terminal, so we need to set up a server using Express.JS.据我了解,浏览器无法从终端读取output,所以需要使用Express.JS搭建服务器。 How can I do this?我怎样才能做到这一点?

Second, as I already mentioned that the second dropdown records should be dependent on the first one, how can we map/link both the arrays?其次,正如我已经提到的,第二个下拉记录应该依赖于第一个,我们如何映射/链接 arrays? For example, when I select Italy in the first dropdown menu, only Italian cities (Milan, Venice, Rome etc) should show up in the second dropdown menu.例如,当 I select Italy 在第一个下拉菜单中时,只有意大利城市(米兰、威尼斯、罗马等)应该出现在第二个下拉菜单中。 If I select Spain, only Spanish cities should show up in the dropdown menu (Madrid, Barcelona etc).如果我 select 西班牙,则只有西班牙城市应显示在下拉菜单中(马德里、巴塞罗那等)。

For reference, the dropdown menu should be something like this作为参考,下拉菜单应该是这样的

I'm a total newbie to NodeJS and any help is appreciated.我是 NodeJS 的新手,任何帮助都将不胜感激。 Thanks.谢谢。

You have asked two questions here.你在这里问了两个问题。 One is how to use express.一是如何使用快递。 The other is how to implement dependent dropdowns.另一个是如何实现依赖下拉。 Perhaps these should be two different questions but let me tackle each one here.也许这应该是两个不同的问题,但让我在这里解决每个问题。 First, how do we use express (which is a web server written in node)一、我们如何使用express(这是一个用node写的web服务器)

1. How to use Express一、如何使用快递

  1. Install express in a directory of your choosing (see link for details)将 express 安装在您选择的目录中(有关详细信息,请参阅链接)
  2. $ npm install express --save
  3. Create a new javascript file新建 javascript 文件
  4. Use the code below使用下面的代码
    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 
    });

This is a simple "hello world".这是一个简单的“hello world”。 I've explained this in detail in this blog .我已在此博客中详细解释了这一点。 If you want to use an html file instead of simple html code, use the following:如果要使用 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);

Note that you will need to use npm or other package to install express, http and fs.请注意,您需要使用 npm 或其他 package 来安装 express、http 和 fs。 Your html code will be in index.html .您的 html 代码将在index.html中。

Your second question is on how to use dependent dropdowns.您的第二个问题是关于如何使用依赖下拉菜单。

2. Dependent dropdowns 2. 依赖下拉菜单

For dependent dropdowns, you are working purely on the client side.对于依赖下拉列表,您纯粹在客户端工作。 So vanilla javascript code will work.所以普通的 javascript 代码可以工作。 For instance, you can use jquery or other useful libraries.例如,您可以使用 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>

Finally see the full working code here最后在这里查看完整的工作代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM