我正在从数据库中检索要作为自动完成列表显示在前端的地址列表。 当我在搜索字段中键入字母时,它显示为空字段。 虽然我可以在控制台上打印json数据。 如果有一些代码片段,那就太好了。
这是我的控制人
package com.searching.controller;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.searching.model.Address;
import com.searching.service.SearchService;
@Controller
public class SearchingController {
@Autowired SearchService searchService;
@RequestMapping(value="/",method=RequestMethod.GET)
public String searchPage() {
//runthismethod();
return "testpage";
}
@GetMapping("/addressAutocomplete")
@ResponseBody
public String getSearchdata(@RequestParam(value="term",defaultValue="",required=false) String term) {
List<Address> address=searchService.fetchAddress();
Gson json=new Gson();
String response=json.toJson(address);
System.out.println(response);
return response;
}
}
前端
<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>jQuery UI Autocomplete functionality</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#automplete-1" ).autocomplete({
source: "/addressAutocomplete",
autoFocus:true,
minLength: 2,
});
});
</script>
</head>
<body>
<!-- HTML -->
<div class = "ui-widget">
<p>Type "a" or "s"</p>
<label for = "automplete-1">Tags: </label>
<input id = "automplete-1">
</div>
</body>
</html>
控制台上的json数据
答案 0 :(得分:0)
只需对控制器进行如下更改,
@GetMapping("/addressAutocomplete")
@ResponseBody
public List<Address> getSearchdata(@RequestParam(value="term",defaultValue="",required=false) String term) {
return searchService.fetchAddress();
}
Spring将返回的数据转换为JSON。