2015-05-02 66 views
0

我想向您尋求幫助,我如何在Spring Web開發中有一個自動完成的搜索框,但我似乎並沒有把它做對嗎?這些是我正在使用的代碼。請幫忙,謝謝!Spring框架:jQuery自動完成搜索框

UserRoleService.java

public interface UserRoleService { 
    List<UserRole> getUserRole(UserRole userRole) String role; 
} 

UserRoleServiceImpl.java

public class UserRoleServiceImpl implements UserRoleService { 
    private UserRoleDao userRoleDao; 

    @Autowired 
    UserRoleServiceImpl(UserRoleDao userRoleDao){ 
     this.userRoleDao = userRoleDao; 
    } 
    public List<UserRole> getUserRole(UserRole userRole, String role)throws Exception{ 
     List<UserRole> userRoleList = userRoleDao.getUserRole(userRoleDao); 
     return userRoleList; 
    } 
} 

控制器

@RequestMapping(value = "userRole", method = RequestMethod.GET) 
public @ResponseBody 
List<UserRole> getUserRole(@RequestParam("term") String role) 
     throws Exception{ 
    List<UserRole> userRoleList = userRoleService.getUserRole(role); 
     ArrayList roleList = new ArrayList(); 
     int count = 0; 
     for(UserRole ei : roleList){ 

      UserRole roleInfo = new UserRole(); 

      roleInfo.put("empUserRole", ei.getUserRole()); 

      roleInfo.put("value", ei.getUserRole()); 
      roleInfo.put("label", ei.getUserRole()); 
      roleList.add(roleInfo); 
      count++; 

      if(count > AUTOCOMPLETE_SIZE){ 
       break; 
     } 
    } 
    return roleList; 
} 

UserRole.jsp

<form:form commandName ="userRoleForm" id="userRoleForm"> 
    <table> 
     <tr> 
      <td>User Role</td> 
      <td><form:input path ="userName" id="empUserRole"/></td> 
     </tr> 
    </table> 
</form:form> 

UserRole.js

$("#empUserRole").autocomplete({ 
    var empRole = { 
     source: "userRole", 
     select: function(event, ui){ 
      $("empUserRole").val(ui.item.empUserRole); 
     }, 
    miLength: 4 
    }; 
}); 

回答

0

empRole這裏看起來可疑,也應該是minLength(您已經錯過了N)。做這樣的事情,而不是

var userRoles; 
     $(function() { 
      $("#empUserRole").autocomplete({ 
       source: function (request, response) { 
        if (typeof userRoles === 'undefined') { 
         $.ajax({ 
          type: "GET", 
          url: "use/proper/url/to/userRole", 
          data: { 
           create:false,         
          }, 
          cache: false, 
          success: function (data) { 
           userRoles = data; 
           response($.ui.autocomplete.filter(userRoles, request.term)); 
          }, 
          error: function() { 
           alert("Error while retrieving Client list(Connection failed)."); 
          } 
         }); 
        } 
       }, 
       minLength: 4 
      }); 
     }); 

它將存儲在userRoles角色,並且確保你使用正確的URL。您從代碼中看到的內容缺少servlet上下文路徑。