Bootstrap 3 typeahead.js - remote url attributes

后端 未结 3 494
孤街浪徒
孤街浪徒 2020-12-10 18:17

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

For now I have this working:

$(\'#league\').typeahead({
        remote: \'/typeah         


        
相关标签:
3条回答
  • 2020-12-10 18:30

    remote is exclusively for typeahead.js (not part of Bootstrap). But you are not using the remote correctly, it can be either a string or an object, not a function.

    When you need to change the request URL, you can use 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
     });
    

    Check the docs here

    Hope it helps.

    0 讨论(0)
  • 2020-12-10 18:47

    Hieu Nguyen solution will not work for %QUERY wildcards. According to Bloodhound.js documentation,

    replace – .... If set, no wildcard substitution will be performed on url.

    Bloodhound docs on github

    So %QUERY will be passed as string without being replaced by text entered from user.

    So you should put typeahead value into your 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
    

    });

    0 讨论(0)
  • 2020-12-10 18:49

    Here is a complete example with the QUERY result as well passed. Note that when the remote method is used variable substitution no longer functions. Thanks to hieu-nguyen for the majority of it!

    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("");
    });
    
    0 讨论(0)
提交回复
热议问题