简体   繁体   English

如何过滤搜索输入以在 JQUERY 中显示正确的自动完成功能?

[英]How to filter search input to show correct autocomplete in JQUERY?

I have a search input where my autocomplete shows but for some reason it the results are not being filtered - can anyone tell or show me a way to filter results to show the correct autocomplete prior in my code below.. Below is the json format and the html code updated.我有一个搜索输入,我的自动完成显示,但由于某种原因,结果没有被过滤 - 谁能告诉我或向我展示一种过滤结果的方法,以在下面的代码中显示正确的自动完成。下面是 json 格式和更新了 html 代码。 Thanks for the help.谢谢您的帮助。

Here is my code这是我的代码

       $( function() {
    var cache = {};
    $( "#searchTextField" ).autocomplete({
      minLength: 2,
      source: function( request, response ) {
        var term = request.term;
        if ( term in cache ) {
          response( cache[ term ] );
          return;
        }

        $.post( "http://localhost:8080/myApp/JobSearchItem.xhtml", request, 
        function( data, status, xhr ) {
          cache[ term ] = data;
          response( data );
        });
      }
    });
  } ); 

JobSearchItem Return JSON JobSearchItem 返回 JSON

[
   {
    "id": "9000",
    "label": "PROGRAMMER TEST 1 (9000) ",
    "value": "90000"
},
 ]

html html

 <h:body>
<f:view transient="true">
  <tp:header/>
  <tp:searchForm/>



  <div id="results">

  </div>

 <h:panelGroup  id="dTable" class="container">
        </h:panelGroup>


</f:view>
   <f:view transient="true">
<div class="jobEntity">
  <div class="job-container-header">
    <h4>#{testBean.jobEntity.toString()}</h4>

    <c:if test="#{testBean.jobEntity.validURLConnection}">
      <a href="#{testBean.jobEntity.pGradeDescriptionLink}" 
         class="btn btn-info-One"   
         target="_blank">[ Test ]</a>
    </c:if>

    <h4>#{testBean.jobEntity.mu} - #{testBean.jobEntity.muDescription}</h4>
    <h4>#{testBean.jobEntity.specialNotes}</h4> 
    <h4>#{testBean.jobEntity.syRgeMnSepMsg}</h4>
  </div>

  <c:if test="${testBean.jobEntity.sectionToDisplay eq 'Range'}">
    <table class="table">
      <tbody>
        <tr>
          <th></th>
          <c:forEach var="stepNumber" begin="1" end="#{testBean.jobEntity.stepSize}">
            <th>Step #{stepNumber}</th>
          </c:forEach>
        </tr>
        <c:forEach items="#{testBean.jobEntity.jobRows}" var="jobRow">
          <tr>
            <th>#{jobRow.rateType}</th>
            <c:forEach items="#{jobRow.steps}" var="step">
              <td>#{step.amount}</td>
            </c:forEach>
          </tr>
        </c:forEach>
      </tbody>
    </table>
  </c:if>
</div>

When you specify a remote URL as the datasource like this, the remote server is expected to do the filtering based on the search term given to it by the autocomplete, and return the results already filtered.当您像这样指定远程 URL 作为数据源时,远程服务器应根据自动完成提供的搜索词进行过滤,并返回已过滤的结果。

Autocomplete only carries out the filtering if you provide it with static data.自动完成仅在您提供静态数据时才执行过滤。 See http://api.jqueryui.com/autocomplete/#option-source for more details.有关更多详细信息,请参阅http://api.jqueryui.com/autocomplete/#option-source

NB If your remote server is unable to do any filtering (eg because it just returns a static file) then you'd have to filter the data client-side in your callback before you return it to the autocomplete.注意如果您的远程服务器无法进行任何过滤(例如因为它只返回一个静态文件),那么您必须在将数据返回到自动完成之前在回调中过滤客户端数据。 But of course this is not very efficient because you keep downloading all the data and then discarding most of it (unless the browser helpfully caches it).但这当然不是很有效,因为您不断下载所有数据,然后丢弃大部分数据(除非浏览器有助于缓存)。

Since you are calling data from a .xhtml file, it is not going to be able to filter the results, unless you can update the server side script to accept and perform activities based on data posted to it.由于您正在从 .xhtml 文件调用数据,因此它无法过滤结果,除非您可以更新服务器端脚本以根据发布到它的数据接受和执行活动。

I would suggest you gather the static data upfront and then filter based on that.我建议您预先收集静态数据,然后根据它进行过滤。 This might look something like:这可能类似于:

$( function() {
  var myData;
  $.get( "http://localhost:8080/myApp/JobSearchItem.xhtml", function( data ){
    myData = data;
  } );
  $( "#searchTextField" ).autocomplete( {
    minLength: 2,
    source: myData
  } );
} );

This assumes that your xhtml is providing a Array of data (usually in JSON format).这假设您的 xhtml 提供了一个数据数组(通常是 JSON 格式)。 This can be simple:这可以很简单:

[
  "Item 1",
  "Item 2",
  "Item 3"
];

Or something more advanced:或者更高级的东西:

[{
  "label": "Item 1",
  "value": 1
},{
  "label": "Item 2",
  "value": 2
},{
  "label": "Item 3",
  "value": 3
}];

If the data you get back is something else: HTML Table, XML, or text, then using a function with Source will help you.如果您返回的数据是其他数据:HTML 表格、XML 或文本,那么使用带有 Source 的函数会对您有所帮助。 If you update your question and provide an example of the data, we could provide a more complete example or guidance.如果您更新问题并提供数据示例,我们可以提供更完整的示例或指南。

Update 1更新 1

Given the following JSON Data:给定以下 JSON 数据:

[{
  "id": "9000",
  "pGrade": "0",
  "label": "PROGRAMMER TEST 1"
},{
  "id": "6000",
  "pGrade": "0",
  "label": "WEB PROGRAMMER TEST 1"
}];

This does not comply with the standard Autocomplete expected data.这不符合标准的自动完成预期数据。 If you are able to POST data to JobSearchItem.xhtml , then you can have it filter first and return data.如果您能够将数据发布到JobSearchItem.xhtml ,那么您可以先对其进行过滤并返回数据。 If JobSearchItem.xhtml does not accept POST, then I would perform a GET of all the data up front and then filter it later.如果JobSearchItem.xhtml不接受 POST,那么我将JobSearchItem.xhtml对所有数据执行 GET,然后再对其进行过滤。 I will include an example of both.我将包括两者的示例。

POST邮政

If you are posting the data, the server-side script needs to know what data you are sending it in the form of a variable name and value.如果您要发布数据,则服务器端脚本需要以变量名称和值的形式知道您发送的是什么数据。 You did not supply a variable name in your example and you have not supplied the JobSearchItem.xhtml content, so it's really hard to identify how this script works.您没有在示例中提供变量名,也没有提供JobSearchItem.xhtml内容,因此很难确定该脚本的工作方式。

For this example, we will use term and our example data will be we .在这个例子中,我们将使用term ,我们的示例数据将是we If this was a GET command, it would look like:如果这是一个 GET 命令,它看起来像:

JobSearchItem.xhtml?term=we

For Post we will use an Object that is submitted:对于 Post,我们将使用一个提交的对象:

{ "term": "we" };

Here are the basics:以下是基础知识:

$(function(){
  var cache = {};
  $("#searchTextField").autocomplete( {
    minLength: 2,
    source: function(request, response){
      var t = request.term;
      if (t in cache){
          response(cache[t]);
          return;
      }
      var results = [];
      $.ajax({
        url: "http://localhost:8080/myApp/JobSearchItem.xhtml",
        data: {
          term: t
        },
        dataType: "json",
        method: "POST",
        success: function( data, status, xhr ) {
          $.each(data, function(k, v){
            results.push({
              label: v.label,
              value: v.label,
              id: v.id,
              grade: v.pGrade
            });
          });
          cache[t] = results;
        });
        response(results);
      });
    }
  });
});

So, in this case, if the user enters we , this is sent to the script, which will filter the results and will send back JSON that should look like:因此,在这种情况下,如果用户输入we ,则会将其发送到脚本,该脚本将过滤结果并发送回 JSON,其应如下所示:

[{
  "id": "6000",
  "pGrade": "0",
  "label": "WEB PROGRAMMER TEST 1"
}];

Since Autocomplete is expecting an object containing label and value can't just be sent direct to response() .由于 Autocomplete 期望包含labelvalue的对象不能直接发送到response() Using $.each() we can iterate the results and adjust so that it's formatted for Autocomplete.使用$.each()我们可以迭代结果并进行调整,以便将其格式化为自动完成。

GET得到

If your obSearchItem.xhtml is static and just provides a list of JSON data, using GET might be a good way to collect this data.如果您的obSearchItem.xhtml是静态的并且仅提供 JSON 数据列表,则使用 GET 可能是收集此数据的好方法。 Consider that you can get all this data up front, and then use it later.考虑到您可以预先获取所有这些数据,然后再使用它。 This is the most common way to use Autocomplete, but the data still has to be in the right format.这是使用自动完成最常用的方法,但数据仍必须采用正确的格式。

$( function() {
  var myData = [];
  $.get("http://localhost:8080/myApp/JobSearchItem.xhtml", function(data){
    $.each(data, function(k, v){
      myData.push({
        label: v.label,
        value: v.label,
        id: v.id,
        grade: v.pGrade
      });
    });
  });
  $("#searchTextField").autocomplete({
    minLength: 2,
    source: myData
  });
});

One of these should work.其中之一应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM