如何将自动完成连接到后端

时间:2013-05-14 05:54:53

标签: javascript jquery jsp struts2

我的代码应该显示用户输入的值的建议,但是我需要从后端检索建议。

我也发现了以下内容,但我想知道是否有使用该列表而不是返回json。

question

以下函数显示了我如何向后端发出请求以提供建议。

从后端检索建议的功能

    function find(value){
                  if(window.XMLHttpRequest)
                {
                    xmlhttp = new XMLHttpRequest();
                }
                else
                {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange=function()
                {
                    if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
                    {
                        document.getElementById("suggestions").innerHTML=xmlhttp.responseText;
                    } 
                }
                xmlhttp.open("get","search?input="+value,false);
                xmlhttp.send();
            }

该函数返回一个建议列表,可以使用for循环显示给用户,如下所示

sug.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

<c:forEach items="${sug}" var="mysug">

       <label id="suggestion" onclick="selectSug('<c:out value="${mysug}"/>')"><c:out value="${mysug}"/></label>
    <br/>
</c:forEach>

代码

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Autocomplete - Multiple values</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    $( "#tags" )
      // don't navigate away from the field on tab when selecting an item
      .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).data( "ui-autocomplete" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        minLength: 0,
        source: function( request, response ) {
          // delegate back to autocomplete, but extract the last term
          response( $.ui.autocomplete.filter(
            availableTags, extractLast( request.term ) ) );
        },
        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;
        }
      });
  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tag programming languages: </label>
  <input id="tags" size="50" />
</div>


</body>
</html>

1 个答案:

答案 0 :(得分:0)

如果在ajax就绪状态下初始化自动完成,则可以使用该列表:

function find(value){
     if(window.XMLHttpRequest)
     {
        xmlhttp = new XMLHttpRequest();
     }
     else
     {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     }
     xmlhttp.onreadystatechange=function()
     {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
             $("#suggestions").html(xmlhttp.responseText);
             //Build up a tag array
             var availableTags=new Array();
             $("#suggestions label").each(function(i,value) {
                  availableTags.push($(value).text());
             });
             //Call a function to initalize your autocomplete when ajax request is ready:
             initAutocomplete(availableTags);
        } 
    }
    xmlhttp.open("get","search?input="+value,false);
    xmlhttp.send();
}

function initAutocomplete(availableTags){
    $("#tags").autocomplete({
       minLength: 0,
       source: function(request, response) {
           response($.ui.autocomplete.filter(availableTags, extractLast(request.term)));
    },
    //[...]
  });
});
}

这比直接调用ajax-source慢,但这样应该是可能的。您还可能遇到$.ajax没有的兼容性问题。另外,我建议不要在每个中使用相同的ID。也许最好使用这样的东西:

<label class="suggestion" onclick="selectSug('<c:out value="${mysug}"/>')"><c:out value="${mysug}"/></label>

然后使用label.suggestion选择器找到建议值。