jquery 在 spring 启动时从数据库自动完成

jquery autocomplete from database in spring boot

我是 Spring 引导新手,

我需要为我的网站做自动完成建议,数据应该从数据库中检索。我想使用 JQuery 自动完成功能。这是我的代码,但它不起作用!使用 Spring 引导以 JSON 形式 have a look.

检索数据

请告诉我,如果我遗漏了什么,或者我写错了什么,或者我提供的来源是错误的,好吧,我在这里找到了 one, it's on php but what matters is jQuery and this one too, and also this video 他在 Spring 启动时做的,我做了同样的事,但还是不行。

这是我的控制器:

@Controller
public class EmpController {
    @RequestMapping(value = "/autocomplete")
    @ResponseBody
    public List<String> autoName(){
        List<String> designation = dao.getDesignation();
        return designation;
    }

    @RequestMapping(value="/save",method = RequestMethod.POST)    
    public String save(@ModelAttribute("emp") Emp emp){
        dao.save(emp);
        return "redirect:/viewemp";
    }

这是我的 jsp:

<body>
<form action="save" method="post">
Name: <input type="text" id="hint" name="hint" >
<input type="submit" name="submit" value="View">
</form>


<!-- JavaScript -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script type="text/javascript" src="/js/main.js"></script>
</body>

这是我的 jQuery:

$(document).ready(function(){
  $("#hint").autocomplete({
      source: "/autocomplete",
      minLength: 1
  });
});

请帮忙..!!

试试这个

   $(function(){
     $.getJSON("http://example:8080/autocomplete", function(data) {
      $( "#hint" ).autocomplete({
         source: data    
           });
        });
    });

无论如何,我觉得你的代码没问题

我也和你一样被卡住了,所以我从头开始..

你不需要从一开始就这样做,这里是自动完成和缩小的代码......

但是请记住,如果您使用 jQuery 来自动完成文本字段,那么您必须在 html 中包含这些脚本和来自 jQuery UI 的 css 链接,或者jsp 文件。

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

控制器:

@Controller
public class EmpController {
    @RequestMapping(value = "/autocomplete")
    @ResponseBody
    public List<String> autoName(@RequestParam(value = "term", required = false, defaultValue = "")String term){
        List<String> designation = dao.getDesignation(term);
        return designation;
    }

}

EmpDao:

@Service
public class EmpDao {

    @Autowired
    private EmpRepository repo;

    @Transactional
    public List<String> getDesignation(String term) {
        return repo.getDesignation(term);
    }
}

存储库:

public interface EmpRepository extends JpaRepository<Emp, Integer> {

@Modifying
    @Query(
            value = "select e.designation from emp69 e where e.designation LIKE %:term%",
            nativeQuery = true
    )
    List<String> getDesignation(String term);

}

JQuery:

$( function() {
    $( "#tags" ).autocomplete({
      source: "autocomplete",
      minLength: 3
    });
  } );

minLength: 3 将使字段在输入字母等于 3 时开始提示

url 您的自动完成页面将是:http://localhost:8080/autocomplete?term=developer

url中的developer是您保存的指定数据。

希望这会有所帮助..