使用nodeJS创建相关的下拉菜单过滤器 [英] Creating dependent dropdown menu filter using nodeJS

查看:76
本文介绍了使用nodeJS创建相关的下拉菜单过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在网页上创建两个下拉菜单-(第二个下拉菜单取决于第一个下拉菜单)-并使用.csv文件的两个不同列中的记录填充这两个菜单。

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.

我能够使用NodeJS读取csv文件,并将所需的列都放入两个不同的数组中,如下所示:

I'm able to read the csv file using NodeJS and get both the required columns into two different arrays as below:

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

这是我到目前为止使用的nodeJS代码:

This is the nodeJS code I've used so far:

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)
});

现在我需要做两件事:首先,我需要在两个不同的下拉列表中填充这两个不同的数组网页上的菜单。 CountryName应该进入第一个下拉菜单,而CityName应该进入第二个下拉菜单。据我了解,浏览器无法读取终端的输出,因此我们需要使用Express.JS设置服务器。我该怎么做?

Now I need to do two things: First I need to populate these two different arrays in two different dropdown menus on a webpage. The CountryName should go into the first dropdown menu and the CityName should go into the second dropdown menu. 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. 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? 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. If I select Spain, only Spanish cities should show up in the dropdown menu (Madrid, Barcelona etc).

作为参考,下拉菜单应为像这样

For reference, the dropdown menu should be something like this

我是NodeJS和任何其他人的新手帮助表示赞赏。谢谢。

I'm a total newbie to NodeJS and any help is appreciated. Thanks.

推荐答案

您在这里问了两个问题。一是如何使用快递。另一个是如何实现依赖下拉列表。也许这应该是两个不同的问题,但让我在这里解决每个问题。首先,我们如何使用express(这是用节点编写的Web服务器)

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)

1。如何使用Express


  1. 在您选择的目录中安装Express(请参阅链接以获取详细信息)

  2. $ npm install express --save

  3. 创建一个新的javascript文件

  4. 使用下面的代码

  1. Install express in a directory of your choosing (see link for details)
  2. $ npm install express --save
  3. Create a new javascript file
  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 
    });

这是一个简单的 hello world。我已经在博客。如果要使用html文件而不是简单的html代码,请使用以下命令:

This is a simple "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:

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或其他软件包来安装express,http和fs。
您的html代码将在 index.html 中。

Note that you will need to use npm or other package to install express, http and fs. Your html code will be in index.html.

您的第二个问题是如何使用

Your second question is on how to use dependent dropdowns.

对于依赖下拉列表,您纯粹是在客户端工作。因此,香草javascript代码将起作用。例如,您可以使用jquery或其他有用的库。

For dependent dropdowns, you are working purely on the client side. So vanilla javascript code will work. For instance, you can use jquery or other useful libraries.

<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

这篇关于使用nodeJS创建相关的下拉菜单过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆