首页 > 代码库 > Struts2的jsonp接口实例
Struts2的jsonp接口实例
和以往写struts2程序一样,action方法跳转到一个JSP中,为了配合jsonp的跨域,要在JSP中做一个输出
JSP:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String jsoncallback = request.getParameter("callback");
String jsonResult = (String)request.getAttribute("jsonStr");
out.println("jsonpcallback("+jsonResult+")");
%>
其中jsonStr是从action层赋值号的,要传给接口的返回值
-------------------------------------------------------------------------------------------------------------
HTML:注意标红的地方!
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script type="text/javascript" src="http://www.mamicode.com/js/jquery-1.11.1.min.js"></script>
</head>
<body>
<script language="javascript">
$.ajax({
type:"get",
dataType:"jsonp",
async:false,
url: "http://localhost:8080/myCwjm/searchJiemus.action",
jsonp:"jsonpcallback",
success: function(response){
}});
function jsonpcallback(response){
alert(response.cate1[0].jmLink);
}
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script type="text/javascript" src="http://www.mamicode.com/js/jquery-1.11.1.min.js"></script>
</head>
<body>
<script language="javascript">
$.ajax({
type:"get",
dataType:"jsonp",
async:false,
url: "http://localhost:8080/myCwjm/searchJiemus.action",
jsonp:"jsonpcallback",
success: function(response){
}});
function jsonpcallback(response){
alert(response.cate1[0].jmLink);
}
</script>
</body>
</html>
也可以在地址栏里直接输入:http://localhost:8080/myCwjm/searchJiemus.action?callback=jsonpCallback
会得到:jsonpcallback({"cate1":[{"jmCate":1,"jmId":1,"jmLink":"http://tv.brtn.cn /20141207/VIDE1417965266460208.shtml","jmName":"和田玉"}, {"jmCate":1,"jmId":2,"jmLink":"http://finance.brtn.cn/20141204 /VIDE1417670950360636.shtml","jmName":"红宝石"}],"cate2": [{"jmCate":2,"jmId":3,"jmLink":"http://finance.brtn.cn/20141128 /VIDE1417156870992643.shtml","jmName":"玛瑙"}, {"jmCate":2,"jmId":4,"jmLink":"http://finance.brtn.cn/20141120 /VIDE1416466960642254.shtml","jmName":"翡翠"}],"cate3":[],"cate4": [],"cate5":[],"cate6":[],"cate7":[],"cate8":[],"cate9":[],"cate10":[],"cate11":[],"cate12":[]})
这样一个json串
Struts2的jsonp接口实例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。