【发布时间】:2016-03-14 11:17:21
【问题描述】:
所以我试图在我网站的导航栏中创建一个搜索表单,并且我正在使用 ajax 提交表单。我的网络应用程序中有其他可用的搜索表单,所以我知道该怎么做。而且我已经正确提交了ajax。我只是不知道如何从表单中获取数据并在控制器中使用它来获得我想要的结果。
我执行搜索功能的方式是创建一个 searchForm.java 对象,该对象具有一个名为 searchString 的字符串变量,然后我填充它,然后使用存储库类中的 spring 数据方法在控制器中的数据库中查询它。
这就是我的 jquery ajax 表单的样子,在 chrome 开发人员工具的控制台中,它返回“setSearch”,就像我在控制器中告诉它的那样,我知道这是个问题,我只是不知道如何解决它。
<script th:inline="javascript">
/*<![CDATA[*/
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
$(document).ready(function(){
$("#searchButton").on("click", function(ev) {
$.ajax({
url : "/setSearch/search",
type : "post",
data : {
"newSearch" : $("#newSearch").val()
},
success : function(data) {
console.log(data);
},
error : function() {
console.log("There was an error");
}
});
});
});
/*]]>*/
</script>
这是我的 thymeleaf html 页面
<form action = "setSearch" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="newSearch"></input>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
</div>
<button type="button" class="btn btn-default" id="searchButton">Search</button>
</form>
这是我的 searchForm.java 对象
public class SearchForm {
private String searchString;
public String getSearchString()
{
return searchString;
}
public void setSearchString(String searchString)
{
this.searchString = searchString;
}
}
这是我的控制器,我知道这不起作用,因为我返回的是字符串而不是 json 对象(我认为这是正确的)。但是我试图改变它,我得到了很多错误,我不知道我应该怎么做。
@RequestMapping(value="/setSearch/search", method=RequestMethod.POST)
public @ResponseBody String search (@RequestParam String newSearch, ModelMap model)
{
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(newSearch);
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
这是我的控制器中的非 ajax 搜索功能的工作示例,所以你们可以看到我正在尝试做什么。
@RequestMapping(value="/setSearch", method=RequestMethod.GET)
public String searchGet(ModelMap model) {
SearchForm searchForm = new SearchForm();
model.put("searchForm", searchForm);
return "setSearch";
}
@RequestMapping(value="/setSearch", method=RequestMethod.POST)
public String searchPost(@ModelAttribute SearchForm searchForm, ModelMap model) {
List<QuestionAnswerSet> questionAnswerSetByQuestion = (List<QuestionAnswerSet>) questionAnswerSetRepo.findByQuestionContaining(searchForm.getSearchString());
model.put("searchResult", questionAnswerSetByQuestion);
return "setSearch";
}
如果我遗漏了任何内容,或者您是否需要查看更多代码来查看我的问题,请告诉我。提前致谢。
【问题讨论】:
标签: ajax spring-mvc spring-data thymeleaf