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>
你想在控制器中選擇機場值的選定值? – amdg
是的。因此,當用戶選擇機場時,它的值(機場的國家,城市,代碼等)顯示在文本字段中,我希望此機場也作爲對象返回給控制器。 – naoumm