我试图让TB Typeahead与 AJAX 结果和 PHP 一起工作,但不能。看到这是我为此编写的代码:
$('#search').typeahead({
limit: 10,
minLength: 2,
source: function() {
return $.ajax({
url: $('base').attr('href') + 'index.php?route=product/search/AjaxProductSearch',
type: "GET",
data: "search=" + $("#search").val(),
success: function(result) {
return result;
}
});
}
});
例如用“co”调用的结果是:
["Combo AMD A4 (14,708.06 BsF)","Combo AMD A8 (17,900.05 BsF)","Combo
Core i3 (17,200.01 BsF)","Combo Core i5 (20,399.95 BsF)","Combo Intel
G465 (13,699.99 BsF)","Combo Intel G630 (15,199.97 BsF)"]
但是没有显示选项,为什么?怎么了?还可以添加一些方法来单击选项并转到特定的 URL?
编辑感谢@dikirill 的惊人帮助,我让这段代码部分工作:
$('#search').typeahead({
limit: 10,
minLength: 2,
source: function(query, process) {
$.ajax({
url: $('base').attr('href') + 'index.php?route=product/search/AjaxProductSearch',
type: "GET",
data: "search=" + $("#search").val(),
success: function(result) {
return process(result.names);
},
dataType: 'json'
});
},
updater: function(item) {
var values = $('#search').data('values');
alert(values);
for (var index in values) {
if (values[index].name == item) {
location.href = values[index].href;
break;
}
}
return item;
}
});
什么不工作?好吧,当我从预先输入的结果中单击任何元素时,我想要立即重定向到与该元素关联的 URL。看到这个 PHP 函数是返回值的函数:
public function AjaxProductSearch() {
$this->load->model('catalog/product');
if (isset($this->request->get['search'])) {
$search = $this->request->get['search'];
} else {
$search = '';
}
$output = array();
if (isset($this->request->get['search'])) {
$data = array(
'filter_name' => $search
);
$product_total = $this->model_catalog_product->getTotalProducts($data);
$results = $this->model_catalog_product->getProducts($data);
$output = array();
foreach ($results as $result) {
$output['names'][] = $result['name'];
$output['values'][] = array(
'name' => $result['name'],
'href' => $this->url->link('product/product', 'product_id=' . $result['product_id'] . $url)
);
}
}
echo json_encode($output);
}
然后返回的一个结果是例如这个:
{"names":["Combo AMD A4","Combo AMD A8","Combo Core i3","Combo Core i5","Combo Intel G465","Combo Intel G630"],"values":[{"name":"Combo AMD A4","href":"http:\/\/store.devserver\/amd-a4"},{"name":"Combo AMD A8","href":"http:\/\/store.devserver\/amd-a8"},{"name":"Combo Core i3","href":"http:\/\/store.devserver\/intel-corei3"},{"name":"Combo Core i5","href":"http:\/\/store.devserver\/intel-corei5"},{"name":"Combo Intel G465","href":"http:\/\/store.devserver\/intel-g465"},{"name":"Combo Intel G630","href":"http:\/\/store.devserver\/intel-g630"}]}
正如您所看到的,我的名称允许我按照必须的方式构建预输入,而其他值是我获得与 href 关联的名称的地方。换句话说,如果我选择Combo AMD A4
然后我应该重定向到href":"http:\/\/store.devserver\/amd-a4
并且我的代码不起作用,有什么问题?
编辑现场演示在这里