在春季启动时从数据库自动查询jQuery

时间:2019-09-10 12:47:07

标签: jquery spring spring-boot autocomplete

我是Spring Boot的新手,

我需要为我的网站进行自动完成建议,并且应该从数据库中检索数据。我想使用JQuery自动完成功能。这是我的代码,但是不起作用!通过使用Spring启动以JSON形式have a look检索数据。

请告诉我我是否丢失了某些东西,或者我写错了什么,或者我提供的来源有错,在这里我确实找到了one,它在php上,但是重要的是jQuery和this one他也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
  });
});

请帮助.. !!

2 个答案:

答案 0 :(得分:1)

尝试一下

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

答案 1 :(得分:1)

无论如何,您的代码对我来说都很好

我也像你一样被困住了,所以我从一开始就做到了。

您不需要从一开始就这样做,这是具有自动完成功能的代码,它也具有缩小的功能...

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

<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
    });
  } );

当输入字母等于3时,minLength: 3将使字段开始建议

您的自动完成页面的

url为:http://localhost:8080/autocomplete?term=developer

URL中的developer是保存为名称的数据。

希望这会有所帮助。