跨域JSONP原理及调用具体示例
<script> var url = "http://localhost:8080/crcp/rcp/t99eidt/testjson.do?jsonp=callbackfunction"; var script = document.createElement('script'); script.setAttribute('src', url); //load javascript document.getElementsByTagName('head')[0].appendChild(script); //回调函数 function callbackfunction(data){ var html=JSON.stringify(data.RESULTSET); alert(html); } </script>
public class TestJson extends ActionSupport{ @Override public String execute() throws Exception { try { JSONObject jsonObject=new JSONObject(); List list=new ArrayList(); for(int i=0;i<4;i++){ Map paramMap=new HashMap(); paramMap.put("bank_no", 100+i); paramMap.put("money_type", i); paramMap.put("bank_name", i); paramMap.put("bank_type", i); paramMap.put("bank_status", 0); paramMap.put("en_sign_ways", 1); list.add(paramMap); } JSONArray rows=JSONArray.fromObject(list); jsonObject.put("RESULTSET", rows); HttpServletRequest request=ServletActionContext.getRequest(); HttpServletResponse response=ServletActionContext.getResponse(); response.setContentType("text/javascript"); boolean jsonP = false; String cb = request.getParameter("jsonp"); if (cb != null) { jsonP = true; System.out.println("jsonp"); response.setContentType("text/javascript"); } else { System.out.println("json"); response.setContentType("application/x-json"); } response.setCharacterEncoding("UTF-8"); Writer out = response.getWriter(); if (jsonP) { out.write(cb + "("+jsonObject.toString()+")"); System.out.println(jsonObject.toString()); } else{ out.write(jsonObject.toString()); System.out.println(jsonObject.toString()); } } catch (Exception e) { e.printStackTrace(); } return null; } }
$(function(){ jQuery.getJSON("http://localhost:8080/crcp/rcp/t99eidt/testjson.do?jsonp=?",function(data) { var html=JSON.stringify(data.RESULTSET); $("#testjsonp").html(html); } ); });
$.ajax({ type:"GET", async :false, url:"http://localhost:8080/crcp/rcp/t99eidt/testjson.do", dataType:"jsonp", success:function(data){ var html=JSON.stringify(data.RESULTSET); $("#testjsonp").html(html); }, error:function(){ alert("error"); } });
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。