【问题标题】:jQuery ui autocomplete with different data sources使用不同数据源的 jQuery ui 自动完成
【发布时间】:2018-07-04 15:06:01
【问题描述】:

我有一个包含多个需要自动完成功能的字段的表单,并且我正在使用“多个”选项,以便每个字段都可以选择多个值。我可以使用单个数据源让一切正常工作。

问题来了:每个字段都需要有一个不同的远程数据源(php 文件输出 JSON 数组)。我想使用自定义的data-attribute 来列出 JSON 数据源 url。

这是我的一个输入的样子: <input type="text" name="frr" id="frr" data-searchsource="searchFrr.php" class="autofillme">

这就是我对 jQuery 的看法——我没有收到任何控制台错误,但它不起作用(自动完成功能根本不再起作用)。如果我在"searchFrr.php" 中为$.getJSON 请求硬编码,一切正常(使用单一数据源)。

任何想法如何使它正常工作?非常感谢您的关注!! :)

$( function() {
    function split( val ) {
      return val.split( /,\s*/ );
}
function extractLast( term ) {
    return split( term ).pop();
}

$('.autofillme').each(function() {

    $(this)
      // don't navigate away from the field on tab when selecting an item
      .on( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).autocomplete( "instance" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        source: function( request, response ) {
          $.getJSON( $(this).data("searchsource"), {
            term: extractLast( request.term )
          }, response );
        },
        search: function() {
          // custom minLength
          var term = extractLast( this.value );
          if ( term.length < 3  ) {
            return false;
          }
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
  });
});

【问题讨论】:

  • “但它不起作用(自动完成功能根本不再起作用)” - 反而会发生什么……?您是否检查过它是否仍然发出任何请求,是否有错误,...?
  • 你检查过$(this)那个时候是什么吗?
  • 说实话,我对 jQuery 并不流利——我正在努力解决这个问题。我花了好几个小时试图用我有限的知识解决这个问题,并广泛搜索、阅读文档并查看 StackOverflow 和其他地方的其他类似问题。考虑到我试图尽可能清楚地提供信息,我觉得投反对票有点苛刻,而且我不只是不费吹灰之力地要求某人为我编写代码。
  • 至于你的问题:会发生什么 - 控制台中没有错误,没有视觉变化,文本字段保持原样。我不确定如何检查是否仍在发出请求,并将对其进行调查,加上明天的 $(this) 是什么,并进行相应的编辑。谢谢。

标签: jquery json user-interface custom-data-attribute


【解决方案1】:

最后,我无法通过我尝试的方法来实现我想要的。我敢肯定,在 jQuery 方面更有成就的人能够弄清楚。

我确实找到了一个解决方案,它允许我根据输入的字段使用不同的数据源。这是使用 jQuery UI 自动完成,带有远程数据源和“多个”选项,因此可以有多个值每个字段选择。我将autofillme 类添加到我想要自动完成的表单中的每个输入。

JAVASCRIPT

$( function() {
  function split( val ) {
    return val.split( /,\s*/ );
}
function extractLast( term ) {
  return split( term ).pop();
}

$('.autofillme').each(function() {

    $(this)
      // don't navigate away from the field on tab when selecting an item
      .on( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).autocomplete( "instance" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        source: function( request, response ) {
          $.getJSON( "searchDB.php", {
            term: extractLast( request.term ),
            // adds an extra query string to the URL, sending the ID of the field sending the request
            field: $(this).attr('element').attr('id')
          }, response );
        },
        search: function() {
          // custom minLength
          var term = extractLast( this.value );
          if ( term.length < 3  ) {
            return false;
          }
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
  });
}); 

PHP - searchDB.php

require "config.php"; // DB credentials stored here

$term = $_GET['term']; // What's been typed so far in the field

$field = $_GET['field']; // The ID of the field that's sending the request
try {
      $connection = new PDO($DB, $username, $password, $options);

        if ($field == 'field_A') {
          $array = $connection->query("SELECT * FROM columnA where value LIKE '%".$term."%'")->fetchAll(PDO::FETCH_ASSOC);
          echo json_encode($array);
        }
        elseif ($field == 'field_B') {
          $array = $connection->query("SELECT * FROM columnB where value LIKE '%".$term."%'")->fetchAll(PDO::FETCH_ASSOC);
          echo json_encode($array);
        }
        elseif ($field == 'field_C') {
          $array = $connection->query("SELECT * FROM columnC where value LIKE '%".$term."%'")->fetchAll(PDO::FETCH_ASSOC);
          echo json_encode($array);
        }
        else {
          // whatever happens if no field sent
        }
      } 
      catch(PDOException $error) {

         echo "A problem has occurred fetching data";
      }

最终,这可能不是一个出色的解决方案,或者特别可扩展,但它完全符合我的要求 - 所以它解决了我的问题。希望它对正在做类似事情的人有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2012-02-09
    • 2011-02-21
    • 2012-02-11
    • 1970-01-01
    • 2011-10-08
    相关资源
    最近更新 更多