【发布时间】:2023-03-17 16:32:02
【问题描述】:
jquery/ajax 的菜鸟来了,请耐心等待! :) 我一直在网上寻找,但没有一个答案能满足我的需求,所以这是我的问题:
我尝试编写代码,现在我需要一个 jquery 函数:
点击按钮后,jquery函数调用指定的控制器方法,
控制器方法从数据库中获取对象数组,
控制器方法将对象数组作为json发送到jsp,
对象数组由同一个 jquery 函数处理,并在我的 jsp 上执行某些操作(例如附加某些 div 的内容)。
现在这是我的代码:
build.gradle 依赖项:
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-tomcat')
compile('org.apache.tomcat.embed:tomcat-embed-jasper')
compile('javax.servlet:jstl')
compile group: 'javax.servlet', name: 'jstl', version: '1.2'
compile group: 'postgresql', name: 'postgresql', version: '9.0-801.jdbc4'
compile group: 'org.webjars', name: 'jquery', version: '2.2.4'
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'
compile group: 'org.webjars', name: 'jquery', version: '2.2.4'
compile("org.springframework.boot:spring-boot-devtools")
compile group: 'org.json', name: 'json', version: '20090211'
compile group: 'com.google.code.gson', name: 'gson', version: '2.3.1'
compile 'javax.validation:validation-api:1.1.0.Final'
compile 'org.hibernate:hibernate-validator:5.0.1.Final'
runtime('com.h2database:h2')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile group: 'com.h2database', name: 'h2', version: '1.3.148'
}
我的 jquery 脚本:
<script>
$(document).ready(function() {
$("#testButton4").click(function(event){
$.ajax({
type : 'GET',
url : '${pageContext.request.contextPath}/fetchComments',
success : function(response) {
$('#result').html(response.get(1).author);
},
error: function() {
alert("God dammit...");
}
});
});
});
</script>
...
<button id="testButton4"> Button4</button>
<div id="result"> Here content should be changed by button click. </div>
...
和我的控制器的代码:
@RequestMapping(value="/fetchComments", method=RequestMethod.GET,produces="application/json")
@ResponseBody
public List<Comment> fetchComments() {
System.out.println("");
System.out.println("Fetching comments from database");
List<Comment> commentList = (List<Comment>) commentRepository.findAllByOrderByIdAsc();
for(Comment comment : commentList){
System.out.println(comment.getId() + ", " + comment.getContent() + ", " + comment.getAuthor()+", "+comment.getPostId());
}
return commentList;
}
目前我的 jquery 函数(成功/错误)都没有工作(我可以在开发工具中看到 json 数据,但从 jquery 的角度来看没有发生任何事情)。我做错了什么?
【问题讨论】:
-
尝试在警报中打印成功响应,同时使用 F12 在控制台中检查您的呼叫响应。