2017-12-02 247 views
0

我试图从自动完成返回到控制器选择。目前自动完成功能正常。我从我的数据库中获得结果到我需要的表单。事情是我也想把这个结果传递给控制器​​来做一些额外的工作。如何使用ajax和jquery将自动完成结果返回给spring mvc控制器

所以我控制器看起来是这样的:

@ResponseBody 
@RequestMapping(value = "/autoCompleteAirportInfo", method = RequestMethod.GET) 
public Map<String, List<AirportInfo>> autoCompleteAirportInfoListAirports(@ModelAttribute("flight")FlightInfo flightInfo) { 
     Map<String, List<AirportInfo>> map = new HashMap<>(); 
     List<AirportInfo> airportList = airportService.findAll(); 
     map.put("airportList", airportList); 
     return map; 
} 

@PostMapping("/autoCompleteAirportInfo") 
public String post(@ModelAttribute("flight") FlightInfo flightInfo) { 
    return "index"; 
} 

的index.html thymeleaf包含的.js:

<script> 
    $(function() { 
     $("#searchAirports").autocomplete({ 
      source: function(request, response) { 
       $.ajax({ 
        url: "/autoCompleteAirportInfo", 
        dataType: "json", 
        data: { 
         maxRows: 6, 
         startsWith: request.term 
        }, 
        success: function(data) { 
         response($.map(data.airportList, function(item) { 
          return { 
           label: item.city + ", " + item.country + ", " + item.code + ", " + item.name, 
           value: item.city + ", " + item.country + ", " + item.code + ", " + item.name 
          } 
         })); 
        } 
       }); 
      }, 
      minLength: 1, 
      open: function() { 
       $(this).removeClass("ui-corner-all").addClass("ui-corner-top"); 
      }, 
      close: function() { 
       $(this).removeClass("ui-corner-top").addClass("ui-corner-all"); 
      } 
     }); 
    }); 

形式

<form form ACTION="#" th:action="@{/autoCompleteAirportInfo}" th:object="${flight}" method="post"> 
       <div> 
        <div> 
         <input type="text" id="searchAirports" placeholder="Search:"/> 
        </div> 
       </div> 
</form> 
+0

你想在控制器中选择机场值的选定值? – amdg

+0

是的。因此,当用户选择机场时,它的值(机场的国家,城市,代码等)显示在文本字段中,我希望此机场也作为对象返回给控制器。 – naoumm

回答

0

我只是通过如下设置一些样本尝试。

@ResponseBody 
@RequestMapping(value = "/autoCompleteAirportInfo", method = RequestMethod.GET) 
public Map<String, List<AirportInfo>> autoCompleteAirportInfoListAirports() { 
     List<AirportInfo> list = new ArrayList<AirportInfo>(); 
     AirportInfo airportInfo = new AirportInfo("A","B","C","D"); 
     list.add(airportInfo); 
     airportInfo = new AirportInfo("E","F","G","H"); 
     list.add(airportInfo); 
     map.put("airportList", list); 
     return map; 
} 

@RequestMapping("/submittedAirport") 
public String post(@RequestParam("searchAirports") String value) { 
    System.out.println("Selected Value="+value) 
    return "index"; 
} 

样品JSP:

... 
<form action=""> 
    <div class="ui-widget"> 
     <input name="searchAirports" id="searchAirports"/> 
    </div> 
    <input type="submit"/> 
</form> 

在提交表单,我能得到POST方法

Selected Value=A, B, C, D 
相关问题