jquery从后台获取json数据

前台页面getData.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:set var="path" value="${pageContext.request.contextPath}"/>

<script language="javascript" src="${path}/js/jquery.js"></script>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>数据处理</title>
<script type="text/javascript">
	$().ready(
		function(){
			$("button").click(function(){
				$.ajax({
					type:"GET",
					url:"http://localhost/项目名/test/json",
					dataType:"json",
					success:function(data){
						alert("name:"+data.name);//从后台获得json数据:name:test
					}
				});
			});
		}		
	);
</script>
</head>
<body>
  <button id="button">获得json</button>
</body>
</html>
后台TestController.java:

@Controller("TestController")
@RequestMapping("/test")
public class TestController {
	@RequestMapping("/json")
	public @ResponseBody String rtnJson(){
		String json = "{\"name\":\"test\",\"sex\":\"female\"}";//这里的json字符串中要注意转义符
		return json;
	}
}
返回json数据:
{"name":"test","sex":"female"}

// TestController 中使用@ResponseBody ,该方法返回 Java对象(支持复杂对象)(也就是把相应的数据绑定到要返回的对象上),MappingJacksonHttpMessageConverter 会将对象转换为 JSON 输出

配置文件中:

<!-- 返回JSON模版,用来处理json格式转换 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean
					class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>
maven配置:

<!--springmvc返回json数据所需坐标 -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.2</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.2</version>
		</dependency>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值