【发布时间】:2013-07-20 17:54:58
【问题描述】:
我正在尝试设置一个非常简单的“HelloWorld”Spring MVC,它将以 JSON 响应用户请求。
我创建了这个 maven 项目 http://www.filedropper.com/mvctest (7 kb)。 要运行它,只需使用 mvn jetty:run
当它启动时,http://localhost:8080/ 会响应
{"name":"John","age":25}
这正是我想要的。现在,我不想在浏览器中输入 http://localhost:8080/,而是想通过 ajax 调用它。
我创建了这个简单的 html 文件:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.ajax({
url:"http://localhost:8080",
success: function(data) { alert("succsess") },
error: function() { alert("error") }
});
});
</script>
</head>
</html>
结果是“错误”。我可以在服务器日志中看到调用了控制器。我可以在 firebug 中看到 JSON 的正确响应,但由于某种原因 JQuery 无法解析它。
当我尝试调用返回 JSon 的不同 URL 时,它起作用了。
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.ajax({
url:"http://ip.jsontest.com/",
success: function(data) { alert("succsess") },
error: function() { alert("error") }
});
});
</script>
</head>
</html>
结果就是成功!我可以在 firebug 的服务器响应中看到一些额外的标头,但我认为这不是问题,其他一切都与我的项目相同。
知道为什么 JQuery 可以正确解释 http://ip.jsontest.com/ 响应而我的则不能?
谢谢, 亚历克斯
P.S.:这里是控制器处理请求的来源
@控制器 公共类 HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public @ResponseBody Person home(Model model) {
logger.info("Welcome home!");
Person person = new Person("John", 25);
return person;
}
public class Person{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
【问题讨论】:
-
你能在控制器上显示响应请求的处理程序吗?
-
可以在这里下载所有源代码的项目filedropper.com/mvctest - 它非常小,只有 7Kb。我用控制器代码更新了问题。
标签: json spring jquery spring-mvc