【发布时间】:2021-02-11 23:25:09
【问题描述】:
我有一个 Thymeleaf 表单。
其中一个输入字段是这样的:
<input type ="text" id="customer" class="floatLabel" name="customer" th:field = "*{customer.idCustomer}">
<label for="customer">Customer</label>
我想使用 jQuery UI。在我的 Java 应用程序中,它可以工作,并且应用程序会发送带有正确值的 JSON。但是我的自动建议列表是空的。
我在我的 html 头部部分包含了一个 css 库,在正文部分的底部包含了几个脚本库。
库是:
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
jQuery 代码:
<script>
$("#customer").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/search_customer",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
// Set selection
$('#customer').val(ui.item.value); // save selected id to input
$('#customer').val(ui.item.label); // display the selected text
return false;
}
});
Java 控制器:
@PostMapping("/search_customer")
@ResponseBody
public List<Object[]> searchTerm(@RequestParam(name = "search", required = false) String searchTerm)
{
List<Object[]> customers = customerDAO.getCustomers(searchTerm);
return customers;
}
JpaRepository:
@Repository
public interface ICustomerRepository extends JpaRepository<CustomerDTO, Integer>
{
@Query(value = "SELECT c.idCustomer, c.ingameName FROM CustomerDTO c WHERE c.ingameName LIKE :term%")
public List<Object[]> findCustomersAutocomplete(String term);
}
所以,一切正常,我得到 JSON 数组,每个元素都有一个整数和一个字符串。在那个 thymeleaf 输入字段中,我希望标签是字符串“ingameName”,值(用户不应该看到)是 idCustomer。
我收到的 JSON 如下所示:
[[1, "customer1"], [3, "Customer2"]]
0: [1, "customer1"]
0: 1
1: "customer1"
1: [3, "Customer2"]
0: 3
1: "Customer2"
所以我希望标签是 customer1 和 Customer2,并且应该保存的值是 1 或 3。 但是不知道怎么告诉jQuery UI什么是label,什么是id?
我遵循了这个教程:
https://makitweb.com/jquery-ui-autocomplete-with-php-and-ajax/
【问题讨论】: