事情:
写js早晚会遇到跨域问题,jsonp为我们提供一个解决方案。
实践一,struts2提供服务端:
1. jsp页面中添加的ajax以jsonp请求
$.ajax({
type: "POST",
url: "<%=basePath %>user/inner/unreadMsg.action",
data: {msgid:msgid},
dataType: "jsonp",
jsonp:"callback",
async: false,
success: function(data, textStatus){
getMsg();
},
error:function(){
}
});
2.struts2中action端配置jsonp返回
@Action(value = "/user/inner/loadMsg", results = { @Result(name = "success", type = "json", params = {"contentType", "text/json","callbackParameter","callback"}) })
public String loadMsg() throws Exception {
msgList = msgPager.getMsgList();
count = msgPager.getCount();
return SUCCESS;
}
实践二,jsp作为服务端
<%
String callback = request.getParameter("callback");
out.print(callback+"({ count:'"+count+"'} );");
out.print(callback);
%>
客户端访问:
$(document).ready(function(){
$.getJSON("http://xxx.test.com/statictis/index.jsp?uid=0001&callback=?", function(json){
alert(json.count);
});
});