[英]Simple search engine with javascript. Any suggestion?
我想用 javascript 做一个简单的搜索引擎。 这个想法是读取服务器端文本文件,对其进行解析并找到与用户查询匹配的任何表达式。 是的,我必须使用客户端脚本。
你有什么建议吗?
谢谢。
编辑 - 回答评论的详细信息
我需要解析 1 个单个文件(最多 10.000 行)。 我不需要自动完成:我只想在 SELECT 元素中显示字符串匹配查询。 另外,如果可能的话,我想避免使用 JQuery。
您将在请求中遇到跨浏览器问题,因此使用抽象此库的库是一个明智的选择。 然而,这里是所需调用的可能框架。
请放心,将大文件存储在 javascript 变量中并不是很方便。 小心你在做什么!
var words = [];
var query = "";
function parseText(data) {
// taking care of data
// check null handle errors
var data = data.replace(/\W+/g,' '); // replace non words with spaces
words = data.split(' '); // split and cache this if you need it again without refetching
doSearch(query);
}
function doSearch(query) {
// handle the loop trough the array
// you may save the data into a variable and use regex instead of splitting into an array
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseXML != null && this.responseXML != "")
// success!
parseText(this.responseXML);
else
parseText(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
parseText(null);
}
}
query = "someword";
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "/remote.txt");
client.send();
如果我理解正确,您需要自动完成。 对于 jQuery 我可以推荐这个。
一些一般性建议:
indexOf
或正则表达式(请记住/foo/.test(str)
比str.match(/foo/)
.) 测试以获取匹配字符串的列表。<options>
。 操作数以千计的 DOM 元素往往要慢得多。 确保 HTML 转义值,并注意您可能会丢失列表中选定的 state(和滚动位置),以防这对您的应用程序很重要。希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.