簡體   English   中英

node.js從html輸入值

[英]node.js inputting values from html

我目前正在node.js中制作一個應用程序,並希望找到一種從html獲取輸入的方法。 當前,我想要一個下拉菜單來調用一個函數,並使用該選擇作為函數的輸入。 但是,當我嘗試調用基本函數(例如console.log('hello world');)時,什么也沒發生。 我正在使用http模塊創建服務器,並使用另一個函數將html返回給本地主機上的用戶。 這是我的代碼片段。

const http = require('http');

http.createServer(function (req, res) {
    var html = buildGreeter(req);
    res.writeHead(200, {
        'Content-Type': 'text/html',
        'Content-Length': html.length,
        'Expires': new Date().toUTCString()
    });
    res.end(html);
}).listen(8080);
function buildGreeter(req) {
var test = 'Test test test   ';
var input = '<select onchange = "myFunc()"> <option> foo </option> <option> bar </option> </select>';
return '<!DOCTYPE html> <html><header></header><body>' + test + input + '</body></html>';
}
function myFunc(variable){
    console.log(variable);
}

我應該使用其他模塊嗎? 我知道很多在線示例都將數據發送到服務器(即通過Ajax),但是由於我沒有該項目的服務器,因此我不知道該解決方案的適用性。

我在這里先向您的幫助表示感謝!

我將使用express節點模塊,可以通過輸入npm i express來安裝它。 這是一個使用express並通過一些實現的方法設置服務器的示例:

const express = require('express')
const renderHtml = require('./util').renderHtml // Render HTML function

let app = express() // Get instance of express server

app.get('/', renderHtml('index.html')) // Home page
app.get('/other', renderHtml('other.html') // Other page

const port = process.env.PORT || 3000
app.listen(port, function() {
  console.log(`Starting server on port ${port}`)
}

在另一個文件(我將其稱為util.js )中,您可以編寫要在服務器上調用某些路徑時要執行的函數。 例如:

// Render any html file that I have in my './html' directory
exports.renderHtml = function (htmlFileName) {
  return function (req, res) { 
    res.sendFile(`./html/${htmlFileName}`)
  }
}

您可以像本例中那樣編寫一個下拉列表,然后使onChange操作成為您在服務器中指定的另一個頁面的調用(例如,請參見第一個代碼塊)。

暫無
暫無

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

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