Ton*_*ami 8 ajax jquery json spring-mvc
我试图通过在SpringMVC 3.0项目中通过Ajax发送州名来获取城市列表.为此,我在JSP中使用了以下调用(使用jQuery):
<script type="text/javascript">
function getCities() {
jq(function() {
jq.post("getCities.html",
{ stateSelect: jq("#stateSelect").val()},
function(data){
jq("#cities").replaceWith('<span id="cities">Testing</span>');
});
});
}
</script>
Run Code Online (Sandbox Code Playgroud)
这是我的控制器代码:
@RequestMapping(value = "/getCities", method = RequestMethod.POST)
public @ResponseBody List<StateNames> getCities(@RequestParam(value="stateSelect", required=true) String stateName,
Model model) {
// Delegate to service to do the actual adding
List<StateNames> listStates = myService.listCityNames(stateName);
// @ResponseBody will automatically convert the returned value into JSON format
// You must have Jackson in your classpath
return listStates;
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,我收到HTTP 406错误说明以下内容: 406 Not Acceptable请求的资源只能根据请求中发送的Accept标头生成不可接受的内容.
我在我的Maven依赖项中使用了Jackson,并在我的上下文文件中定义了.我已经广泛搜索了,我猜问题是@ResponseBody不会自动将我的List转换为适当的JSON对象.
我的Firebug说:
Response Headers
Server Apache-Coyote/1.1
Content-Type text/html;charset=utf-8
Content-Length 1070
Date Sat, 12 Feb 2011 13:09:44 GMT
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13
Accept */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Content-Type application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/MyApplication/
Content-Length 17
Cookie JSESSIONID=640868A479C40792F8AB3DE118AF12E0
Pragma no-cache
Cache-Control no-cache
Run Code Online (Sandbox Code Playgroud)
请指导我.我究竟做错了什么??救命!!
正如彼得在评论中写道的那样,问题的原因是Spring无法加载杰克逊.默认情况下,它不会被依赖项加载.在我添加了依赖项之后
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
在浏览器中键入地址后返回了JSON,没有任何带有Accept标头的技巧(正如它应该做的那样).
在Tomcat 7.0上测试过.
你有错误的响应内容类型它应该是application/json.
您需要将jackson添加到/ lib目录中.
你应该有
<mvc:annotation-driven />
Run Code Online (Sandbox Code Playgroud)
在您的serlvet-name.xml文件中.
此外,我建议您将您的请求映射为get并尝试使用Google Chrome进行浏览,以查看它是否返回正确的结果.它具有非常好的json表示.
| 归档时间: |
|
| 查看次数: |
17769 次 |
| 最近记录: |