在spring mvc环境中用Ajax抓取JSON

本文解释如何抓取JSON,用Ajax,从spring web应用中。它以带注释的spring mvc和用spring mvc服务静态资源的例子为基础。代码在github的spring-fetching-json-with-ajax目录下.

主index页面
我们用一个简单的index.jsp页面,上面设置一个按钮抓取json,一个<div>元素,这里显示结果。 

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8">
  <script type="text/javascript"
	src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script type="text/javascript"
	src="<c:url value='/resources/js/FetchingJsonWithAjax.js'/>">
  </script>
  <title>Welcome To Fetching JSON With Ajax !!!</title>
</head>
<body>
    <h1>Fetching JSON With Ajax !!!</h1>
	<div id="theJson"></div>
	<button type="button" οnclick="fetch_json()">
		Fetch JSON
	</button> 
</body>
</html>
Javascript
我们把fetch_json()方法加到按钮上,当单击按钮时,这个方法被调用。  

var fetch_json = function() {
	
    $.ajax({
        type: 'GET',
        url:  "/sprJSON/getJSON",
		dataType: 'json',
        async: true,
        success: function(result) {
			
			var tmp = "Fetch time is: " + result.milliTime + " !"
			   + "<br /><br />and the JSON is:<br /><br />"
		       + JSON.stringify(result) + "<br /><br />";
			
			$("#theJson").html(tmp);
			
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("Issue fetching the JSON: "
				+ textStatus + " "
				+ errorThrown + " !");
        }
    });
    
}
如果成功了,我们就把结果写到<div>中,否则就弹出一个错误提示框!
控制器
写得很简单,针对Ajax的调用,我们返回了一个Millitime对象.      

@Controller
public class MyController {
	
	@RequestMapping(value = "/")
	public String home(Model model) {
		return "index";
	}
	
	@RequestMapping(value="/getJSON", method = RequestMethod.GET)
    public @ResponseBody MilliTimeItem getJSON() {
		return new MilliTimeItem(System.currentTimeMillis());
    }
	
}

运行程序:

原文:http://technotes.tostaky.biz/2012/11/fetching-json-with-ajax-in-spring-mvc-context.html

源代码:http://pan.baidu.com/share/link?shareid=2748138567&uk=3878681452


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值