在spring mvc环境中用Ajax抓取JSON

来源:互联网 发布:python 盗取账号密码 编辑:程序博客网 时间:2024/05/22 10:27

本文解释如何抓取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" onclick="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对象.      

@Controllerpublic 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


原创粉丝点击