Typeahead Bloodhound POST request

后端 未结 3 556
心在旅途
心在旅途 2020-12-24 08:08

I cannot seem to get a remote query to use POST properly.

var creditors = new Bloodhound({
    datumTokenizer: function (d) {
        return Bloodhound.token         


        
相关标签:
3条回答
  • 2020-12-24 08:40

    You can use beforeSend of $.ajax

    var creditors = new Bloodhound({
        datumTokenizer: function (d) {
            return Bloodhound.tokenizers.whitespace(d.value)
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: "../getCreditors",
    
            replace: function(url, query) {
                return url + "#" + query;
            },
            ajax : {
                beforeSend: function(jqXhr, settings){
                   settings.data = $.param({q: queryInput.val()})
                },
                type: "POST"
    
            }
        }
    });
    
    0 讨论(0)
  • 2020-12-24 08:46

    You can use the prepare property with remote or prefetch, mind that the function signature changes. An example with prefetch:

    var Bloodhound = new Bloodhound({
                    datumTokenizer: Bloodhound.tokenizers.whitespace,
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    prefetch: {
                        url: remote,
                        prepare: function (settings) {
                            settings.type = "POST";
                            settings.contentType = "application/json; charset=UTF-8";
                            return settings;
                        },
                        remote: function (query, settings) {
                            settings.type = "POST";
                            settings.data = {q: query, foo: 'bar'}; // you can pass some data if you need to
                            return settings;
                        }
                    }
                });
    

    Remember that with remote the function signature changes with function(query, settings).

    For reference: github.com/twitter/typeahead.js/issues/1236

    0 讨论(0)
  • 2020-12-24 09:00

    I found the ajax 'beforeSend' method holylaw mentioned worked the best.

    It was important to alter the url as well though. Otherwise Typeahead didn't bother making another request. So I just added a bogus parameter at the end of the url. Like this

    http://mylittleservice.com?blah=%QUERY

    That way when the ajax data packaged changed I was assured a fresh request to the server.

    0 讨论(0)
提交回复
热议问题