我正在尝试使搜索引擎向上搜索键以从DB返回结果,而且还键入了短语以从非DB的对象中提取结果。>
例如:当您键入“ BMW 300”时,将从数据库中提取数据并将短语和结果保存在object中,而object看起来像这样
object { b: (4) […] 0: Object { name: "BMW"} 1: Object { name: "BMW 300"} 2: Object { name: "BMW XS"} 3: Object { name: "BMW Z 500"} bm: (4) […] 0: Object { name: "BMW"} 1: Object { name: "BMW 300"} 2: Object { name: "BMW XS"} 3: Object { name: "BMW Z 500"} bmw: (4) […] 0: Object { name: "BMW"} 1: Object { name: "BMW 300"} 2: Object { name: "BMW XS"} 3: Object { name: "BMW Z 500"} "bmw 3": (1) […] 0: Object { name: "BMW 300"} "bmw 30": (1) […] 0: Object { name: "BMW 300"} "bmw 300": (1) […] 0: Object { name: "BMW 300"} }
如果您删除了300个短语,则该短语变为“ BMW”,因为已经键入了短语“ BMW”,现在应该从对象中提取结果。
我既对逻辑进行编码,又能完美地工作,但是问题是如何交换何时从对象读取以及何时从DB读取?
// create object
var hold_results = {};
$('input[name="search"]').on('keyup', function(){
var phrase = jQuery.trim($(this).val());
if (phrase.length > 0) {
$.ajax({
type: "POST",
url: 'index.php?route=product/newsearch',
data: 'phrase='+phrase,
success: function(data) {
if (data.length != 0) {
// push phrase and currect results in object
hold_results[phrase] = data;
$.each(data , function(key, value){
if (value != '') {
html = '<li><a href="'+value.href+'">'+value.name+'</a></li>';
$('#search-results').append(html);
}
});
}
}
});
}
// should pull results from object here if phrase exist
$.each(hold_results , function(key , value){
if (key == phrase) {
$.each(value, function(k , v){
html = '<li><a href="'+v.href+'">'+v.name+'</a></li>';
$('#search-results').append(html);
})
}
});
});
[我正在尝试使搜索引擎向上键以从数据库返回结果,而且还键入了短语以从非数据库对象中检索结果,例如:当您键入“ BMW 300”时将检索数据...]
您可以简单地检查phrase
对象中是否已经存在holds_results
,以及是否不从db中获取它
// create object
var hold_results = {};
$('input[name="search"]').on('keyup', function(){
var phrase = jQuery.trim($(this).val());
if (phrase.length > 0) {
if (hold_results[phrase]) {
// should pull results from object here if phrase exist
$.each(hold_results , function(key , value){
if (key == phrase) {
$.each(value, function(k , v){
html = '<li><a href="'+v.href+'">'+v.name + '</a></li>';
$('#search-results').append(html);
})
}
});
}
else {
$.ajax({
type: "POST",
url: 'index.php?route=product/newsearch',
data: 'phrase=' + phrase,
success: function (data) {
if (data.length != 0) {
// push phrase and currect results in object
hold_results[phrase] = data;
$.each(data, function (key, value) {
if (value != '') {
html = '<li><a href="' + value.href + '">' + value.name + '</a></li>';
$('#search-results').append(html);
}
});
}
}
});
}
}
});
有一个简单的方法可以实现这一目标-但是首先,您需要意识到您的实现会多次执行并且可能无法按预期运行。我会考虑添加一些内容: