5

I'm trying to call my remote url with added attributes to the url.

For now I have this working:

$('#league').typeahead({
        remote: '/typeahead/get_league?query=%QUERY',
        limit: 10
});

Now I would like to do something like this:

$('#league').typeahead({
        remote: function () {
            var q = '/typeahead/get_league?query=%QUERY';
            if ($('#sport').val())
                q += "&sport=" + encodeURIComponent($('#sport').val());
            return base_url + q;
        },
        limit: 10
});

I would like to add the GET attribute 'sport' to the URL so I can narrow down my query on the backend. I tried the code above but I get a JS error.

The previous version of Bootstrap Typeahead allowed this type of setup. It was very useful as I could update the remote URL every time a key get hit.

Any idea how to make that work for this version ?

4

3 回答 3

10

remote专门用于typeahead.js(不是 Bootstrap 的一部分)。但是您没有remote正确使用它,它可以是字符串对象,而不是函数。

当您需要更改请求 URL 时,可以使用replace

$('#league').typeahead({
    remote: {
        url: '/typeahead/get_league?query=%QUERY',
        replace: function () {
            var q = '/typeahead/get_league?query=%QUERY';
            if ($('#sport').val()) {
                q += "&sport=" + encodeURIComponent($('#sport').val());
            }
            return base_url + q;
        }
    },
    limit: 10
 });

在此处查看文档

希望能帮助到你。

于 2013-08-09T07:40:51.147 回答
5

Hieu Nguyen 解决方案不适用于 %QUERY 通配符。根据 Bloodhound.js 文档,

replace - ....如果设置,则不会对 url 执行通配符替换。

github 上的 Bloodhound 文档

因此 %QUERY 将作为字符串传递,而不会被用户输入的文本替换。

因此,您应该将 typeahead 值放入您的 url :

$('#league').typeahead({
remote: {
    url: '/typeahead/get_league?query=%QUERY',
    replace: function () {
        var q = '/typeahead/get_league?query=' + $('#league').val();
        if ($('#sport').val()) {
            q += "&sport=" + encodeURIComponent($('#sport').val());
        }
        return base_url + q;
    }
},
limit: 10

});

于 2015-01-16T10:03:11.570 回答
1

这是一个完整的示例,其中 QUERY 结果也通过了。请注意,当使用远程方法时,变量替换不再起作用。感谢hieu-nguyen的大部分工作!

jQuery('#city').typeahead({
    name: "cities",
    remote: {
        url: current_web_root + '?action=ajax|getcities&query=%QUERY',
        replace: function () {
            var q = current_web_root + '?action=ajax|getcities&query=' + jQuery('#city').val();
            if (jQuery('#state').val()) {
                q += "&state=" + encodeURIComponent(jQuery('#state').val());
            }
            return q;
        }
    },      
    cache: false
}); 

jQuery("#state").change(function (e) {
    jQuery('#city').val("");
});
于 2013-09-10T17:22:02.730 回答