首页 > 解决方案 > JavaScipt 中的输入处理

问题描述

我是 Web 开发(包括 JavaScript 和 HTML)的新手,并且在我的个人项目中遇到了一些似乎没有明确修复的问题。

概述

我的项目是从网站上的用户那里获取输入,并将其提供给我的后端以输出单词完成建议列表。

例如,输入 => "bass",那么程序会建议 "bassist"、"bassa"、"bassalia"、"bassalian"、"bassalan" 等作为模式 "bass" 的可能补全(这些是单词从英语词典文本文件中提取)。

后端 - 在 Node JS 库上运行

trie.js file:

/* code for the trie not fully shown */

var Deque = require("collections/deque"); // to be used somewhere

function add_word_to_trie(word) { ... }
function get_words_matching_pattern(pattern, number_to_get = DEFAULT_FETCH) { ... }

// read in words from English dictionary

var file = require('fs');
const DICTIONARY = 'somefile.txt';

function preprocess() {
    file.readFileSync(DICTIONARY, 'utf-8')
        .split('\n')
        .forEach( (item) => {
        add_word_to_trie(item.replace(/\r?\n|\r/g, ""));
    });
}

preprocess();

module.exports = get_words_matching_trie;

前端

呈现网站视觉效果的 HTML 脚本,以及从用户那里获取输入并将其传递到后端脚本以获得可能的建议。它看起来像这样:

index.html script:

<!DOCTYPE HTML>
<html>

   <!-- code for formatting website and headers not shown -->
   <body>
            <script src = "./trie.js">

                function get_predicted_text() {
                    const autofill_options = get_words_matching_pattern(input.value);
                    
                    /* add the first suggestion we get from the autofill options to the user's input
                     arbitrary, because I couldn't get this to actually work. Actual version of                                                                                                     
                     autofill would be more sophisticated. */

                    document.querySelector("input").value += autofill_options[0];
                }
                
            </script>

            <input placeholder="Enter text..." oninput="get_predicted_text()">
            <!-- I get a runtime error here saying that get_predicted_text is not defined -->
   </body>
</html>

我得到的错误

首先,我得到客户端未定义“require()”的明显错误。这个,我用browserify修复。

其次,作为 node.js 模块,客户端不存在“fs”的问题。我尝试使用 node 运行 trie.js 文件并使用一些服务器端代码处理它:

function respond_to_user_input() {
    fs.readFile('./index.html', null, (err, html) => {
        if (err) throw err;

        http.createServer( (request, response) => {
            response.write(html);
            response.end();
        }).listen(PORT);

    });

respond_to_user_input();
}

有了这个,我不完全确定如何编辑文档元素,例如更改input.valueindex.html,或在输入字段中调用oninput事件侦听器。此外,如果我通过node trie.js终端中的命令调用 HTML 文件,则不会调用我的 CSS 格式化脚本。

这给我留下了一个问题:是否甚至可以直接运行 index.html(通过 Google Chrome)并在调用 trie.js 脚本时让它使用节点 JS 模块?我可以使用 HTTP 模块在上面描述的服务器端代码,我如何解决调用我的外部 CSS 脚本(我的 HTML 文件发送一个 href 到)和访问 document.querySelector("input") 来编辑我的输入的问题场地?

标签: javascripthtmlnode.jshttpweb-deployment-project

解决方案


推荐阅读