如何在键入输入文本时进行ajax调用并返回结果

我想实现一些function,当我输入一些文本时

 

应该会出现一个建议标签列表 产品关键词

在进行ajax调用之后。 我有数据库查询

 public interface TagRepository extends JpaRepository { @Query("SELECT t FROM Tag t WHERE name LIKE CONCAT('%', :name, '%')") List findTagByName(@Param("name") String name); } 

和控制器代码是

 @RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json") public @ResponseBody List getTags(@RequestBody Tag tag, HttpServletResponse response) { System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size())); return tagService.findTagByName(tag.getName()); } 

jj for ajax是

  $(document).ready(function() { $("#tag-search").autocomplete({ source: function(request, response) { $.ajax({ url: "/app/getTags/", type: "POST", data: JSON.stringify({tag : request.term}), dataType: "json", success: function(data) { response($.map(data, function(v,i){ console.log(); return { label: v.empName, value: v.empName }; })); } }); } }); }); 

当我运行应用程序时,我在开发人员工具中看到了这个javaScript错误 快照

重要

我正在使用Daemonite /材料作为我的前端和jQuery-Autocomplete ,最后一个好处是最新版本的App 在GitHub可以任何人告诉我如何摆脱错误任何响应是受欢迎的。

检查jquery供应商库是否正确加载。

交叉检查:

  

对于上面的问题,我主要使用select2 jquery插件 。 它有很多内置function,所以不需要重新发明轮子。 查看此链接以获取演示 – http://select2.github.io/select2/#infinite

屏幕截图:

在此处输入图像描述

代码示例:

 $("#e7").select2({ placeholder: "Search for a repository", minimumInputLength: 3, ajax: { url: "https://api.github.com/search/repositories", dataType: 'json', quietMillis: 250, data: function (term, page) { // page is the one-based page number tracked by Select2 return { q: term, //search term page: page // page number }; }, results: function (data, page) { var more = (page * 30) < data.total_count; // whether or not there are more results available // notice we return the value of more so Select2 knows if more results can be loaded return { results: data.items, more: more }; } }, formatResult: repoFormatResult, // omitted for brevity, see the source of this page formatSelection: repoFormatSelection, // omitted for brevity, see the source of this page dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results }); 

现在布局与您提供的屏幕截图不完全相同,但请检查此布局是否适合您。

更新:

 function repoFormatResult(repo) { var markup = '
' + '
' + '
' + '
' + '
' + repo.full_name + '
' + '
' + repo.forks_count + '
' + '
' + repo.stargazers_count + '
' + '
'; if (repo.description) { markup += '
' + repo.description + '
'; } markup += '
'; return markup; } function repoFormatSelection(repo) { return repo.full_name; }

另一种方法:

嗨,如果以上解决方案不适合您的问题,那么你可以使用这个。 它被称为typeahead.js是一个由twitter提供的JavaScript库。 你可以在这里找到例子。

它只是意味着你得到的是HTML而不是JSON作为回应。

意外< ”指的是请求响应的第一个字符。 在Chrome控制台中,您可以转到网络选项卡并单击您的请求,然后在右侧查看您的服务器返回客户端的确切内容。

你错过了jquery.js。 添加它,你会得到它的工作。

我在这里添加代码,以便更好地阅读;

在返回jquery之前,编写一个新方法来解析Java端的json。 当前代码返回Java列表作为Ajax的输出,这可能会抛出未捕获的语法错误:意外的令牌。

  public static String toJSON(Object object) { if ( object == null ){ return "{}"; } try { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(object); } catch (Exception e) { e.printStackTrace(); } return "{}"; } 

对于上面的代码,你需要包括3个jars jackson-core-2.2.3.jar,jackson-annotations-2.2.3.jar和jackson-databind-2.2.3.jar。

改变你的控制器如下;

 @RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json") public @ResponseBody String getTags(@RequestBody Tag tag, HttpServletResponse response) { System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size())); return toJSON(tagService.findTagByName(tag.getName())); } $(document).ready(function() { var autoCompleteResult = ''; $("#tag-search").autocomplete({ source: function(request, response) { $.ajax({ url: "/app/getTags/", type: "POST", data: JSON.stringify({tag : request.term}), dataType: "json", success: function(data) { autoCompleteResult = jQuery.parseJSON(data); response($.map(autoCompleteResult, function(v,i){ console.log(); return { label: v.empName, value: v.empName }; })); } }); } }); }); 

尝试此操作后请分享您的结果。

试试这个: https : //github.com/tanwaniniranjan/autosuggest这是一个为同样目的而制作的插件。 文档很少,但我希望尽快提出文档。

Yu可以阅读js文件中的注释,以了解其用法

编辑:我现在更仔细地阅读您的问题,发生的事情是:您从服务器端获得的响应是​​错误的。 这个错误通常会像对不起兄弟404那样开始

因为你试图映射数据,jQuery只是无法解析它,它会给你错误。 首先检查你的服务器端。 使用postman插件发出请求,validation您的响应,然后实现jQuery: https : //chrome.google.com/webstore/detail/postman-launcher/igofndmniooofoabmmpfonmdnhgchoka?hl = en

正如我所看到的,可能存在500 internal server error的问题,因为你有一个dataType: "json",在你的ajax中,而你的控制器你没有返回任何json

 @RequestMapping(value = "/getTags", method = RequestMethod.POST, produces = "application/json") public @ResponseBody List getTags(@RequestBody Tag tag, HttpServletResponse response) { System.out.println("Found " + String.valueOf(tagService.findTagByName(tag.getName()).size())); return tagService.findTagByName(tag.getName()); } 

在你的控制器这里:produce produces = "application/json"表示它将返回json作为输出并使用: return tagService.findTagByName(tag.getName()); 你可以生产任何json

只需将以下标记添加到您的ajax调用即可

  contentType: 'application/json; charset=utf-8', 

这是请求数据的类型,在您的情况下,它只是您在文本框中键入的文本格式

如果您的响应数据不是json类型,请从您的ajax调用中删除以下行

dataType: 'json',这可能会删除代码中的Json解析错误

如下所示更改您的JavaScript

 $(document).ready(function() { $("#tag-search").autocomplete({ source: function(request, response) { $.ajax({ contentType: 'application/json; charset=utf-8', url: "/app/getTags/", type: "POST", data: JSON.stringify({'tag' : "'"+request.term+"'"}), dataType: "json", success: function(data) { response($.map(data, function(v,i){ console.log(); return { label: v.empName, value: v.empName }; })); } }); } }); });