码迷,mamicode.com
首页 > Web开发 > 详细

Struts2的jsonp接口实例

时间:2014-12-10 12:15:08      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   io   ar   color   os   sp   java   

和以往写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串
 
 

Struts2的jsonp接口实例

标签:des   style   http   io   ar   color   os   sp   java   

原文地址:http://www.cnblogs.com/loveLearning/p/4154929.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!