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="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串
 
 
posted @ 2014-12-10 11:02  积累从点滴开始  阅读(3489)  评论(0编辑  收藏  举报