【发布时间】:2015-08-13 00:47:40
【问题描述】:
我有一个巨大的 JSON 文件,我一直在使用它通过 JavaScript 和 AJAX 进行搜索。我正在使用实时搜索,因此每次按键后,JavaScript 都会搜索整个 JSON 文档并返回与搜索字段中的内容匹配的结果。
问题是每次我按下一个键时,服务器都会请求整个 JSON 文件,这会导致数据使用量迅速增加。
有没有办法将整个 JSON 文件下载到本地机器上然后执行搜索?
我一直在使用 JQuery 的 $.getJSON() 作为解释 JSON 文件的方法。
我想要一个尽可能减少更改现有代码的解决方案。
我在想也许将 JSON 复制到 HTML 文件中效果最好,因为一旦页面加载,它就会全部下载,我可以在 HTML 中搜索它。虽然我不知道该怎么做。
这是我的 JSON 数据的样子:(其中有近 500 个除外)
{"profiles": [
{
"first_name": "Robert",
"last_name": "Hosking",
"img_url": "img/about/profile.jpg",
"major": "Computer Science",
"cohort": 12,
"bio": "eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi",
"linkedin": "http://linkedin.com",
"home_town": "Rutherfordton, NC",
"status": "Student"
}]
这是我的搜索功能的样子:(在我的 HTML 中有一个带有 id="search" 的输入字段)
$('#search').keyup(function() {
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('/profiles.json', function(data){
var result =""
$.each(data.profiles, function(key, val){
var fullName = val.first_name + " " + val.last_name
var cohortNum = val.cohort.toString()
var cohortName = "cohort " + cohortNum
if ((val.first_name.search(myExp) != -1) ||
(val.last_name.search(myExp) != -1) ||
(val.major.search(myExp) != -1) ||
(fullName.search(myExp) != -1)||
(cohortNum.search(myExp) != -1)||
(cohortName.search(myExp) != -1)
){
var template = $('#profile-preview-template').html();
result += Mustache.render(template, val);
}
});
$('#profile-results').html(result);
});
});
Mustache.render(template, val) 只是将 JSON 数据从一个名为 mustache.js 的库中输入到 JavaScript 模板中。
提前致谢!
【问题讨论】:
标签: javascript jquery ajax json