如何使用ajax和jquery将自动完成结果返回给spring mvc控制器
我试图从自动完成返回到控制器选择。目前自动完成功能正常。我从我的数据库中获得结果到我需要的表单。事情是我也想把这个结果传递给控制器来做一些额外的工作。如何使用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>
回答:
我只是通过如下设置一些样本尝试。
@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
以上是 如何使用ajax和jquery将自动完成结果返回给spring mvc控制器 的全部内容, 来源链接: utcz.com/qa/258433.html