【问题标题】:Prevent ajax call on empty spaces typeahead.js防止在空白处调用 ajax typeahead.js
【发布时间】:2017-05-06 19:03:51
【问题描述】:

我一直在使用typeahead.js 并使用BloodHound remote 选项加载数据。

除了当我在textbox 中输入only spaces 时,一切都按预期工作,仍然sends ajax call

如果文本框中有only spaces,我想知道是否有办法prevent ajax call。我正在寻找类似trim 的行为。

这是我的代码。我曾尝试使用prepare 函数,但没有成功。

var dataSource = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('ProductID', 'ProductName'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
              url: urlVar + "LoadAllProductByProductName/%QUERY",
              wildcard: '%QUERY',

            },
    sufficient: 3,
   });

const $tagsInput = $('.txtProductName')
$tagsInput.typeahead({
   minLength: 3,
   source: dataSource,
   hint: false,
   highlight: true,
   isBlankString: false
   },
   {
      limit: 10,
      source: dataSource,
      name: 'dataSource',
      display: function (item) {
         return item.ProductName
      },
      suggestion: function (data) {
         return '<div>' + data.ProductName + '–' + data.ProductID + '</div>'
      },

});

【问题讨论】:

  • 为什么在有空格的情况下发送呼叫会出现问题?大概用户不会得到任何结果。
  • 我想避免网络旅行。
  • 假设每次用户键入超过 3 个字符的 anything 时都会生成一次网络旅行,并且用户实际键入 3 个空格的可能性(它们不太可能认为它会返回任何东西!),您可能会付出很多努力并将网络流量减少 0.0001%。光说好像有点没意思。但是,如果您真的想要,您可以为 source 属性创建一个自定义函数,并根据搜索词阻止请求继续进行(并且只返回一个空数组)。 typeahead 文档显示方法签名
  • 看这个example

标签: javascript jquery ajax twitter-bootstrap typeahead.js


【解决方案1】:

我会尝试将 keyUp 事件附加到文本框以执行过滤:

$tagsInput.keyup(function(){
        this.value = this.value.replace(/  */, ' ');
    });

这将在第二个空格之后触发,这应该可以减轻不良行为,除非该字段中也有非空格字符。

【讨论】:

  • 我认为这是可能的方式
  • 即使它有效,它也不是我正在寻找的那种解决方案。如果您确定没有惯用的方法,我更喜欢作为答案。
【解决方案2】:

remote 属性有一个prepare 函数,您可以在调用通过网络之前使用该函数处理此更改。

举个例子:

function createBloodHoundConfig(options) {
    return {
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        identify: options.identify,
        sufficient: 8,
        remote: {
            url: options.url,
            prepare: function (query, settings) {
                settings.url = settings.url.replace("{q}", query.trim());
                return settings;
            }
        },
    };
}

请注意,在这种情况下,您不提供 wildcard 属性,因为它实际上是进行令牌替换的简写。

【讨论】:

  • 这不会阻止通话。它只是 trims 搜索的内容。
【解决方案3】:

为什么不试试这个?

prepare: function (query, settings) {
                    var word = $.trim(query);
                    if(word){
                        settings.url = "/search?q=" + 
                       word;
                        return settings;
                    }
                },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多