跨域访问:jquery ajax jsonp的实现方法(jsp和action方式)
- <mce:script language="javascript"><!--
- $(function(){
- $.ajax({
- type: "get",
- url: "www.sssss.com/ddd.do",
- data: {
- area : "ddd",
- areaid : "2",
- categorySz : ["",
- "",
- "",
- "",
- "",
- "208",
- "",
- "",
- "205",
- "205",
- "206"
- ,"207,250,251,252,253"
- ,"207,254"
- ,"207,255"
- ,"207,256"
- ,"207,257"
- ,"207,258"
- ,"207,259"],
- typeSz : ["520,1201,201",
- "520,1201,202",
- "520,1202",
- "520,1203",
- "520,1204",
- "",
- "521,1201,201",
- "521,1201,202",
- "1201,202",
- "1202"
- , ""
- , ""
- , ""
- , ""
- , ""
- , ""
- , ""
- , ""],
- categoryOrSz : ["",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- ""
- , ""
- , "250,251,252,253"
- , ""
- , ""
- , ""
- , ""
- , ""
- , ""]},
- dataType : "jsonp",
- jsonp: "callback",
- async: false,
- cache: false,
- success: function(data){
- if (data != null && data != "") {
- }
- }
- });
- });
- // --></mce:script>
服务器端:
代码很简单,就是输出一个字符串
比如正常输出json应该是:[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]
jsonp 则输出: jsonpcallback([{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]) 其中“jsonpcallback”是客户端传过来的
- /**
- *
- * @param form
- * @param request
- * @param response
- * @return
- * @throws Exception
- */
- public String ajaxGetMybusAllDataJsonp(ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- String callback = request.getParameter("callback");
- JSONObject res = new JSONObject();
- /*
- * 处理方法
- *
- */
- res.put("d", "dddd");
- // 可以避免前台显示出现乱码
- response.setContentType("text/html");
- response.setCharacterEncoding("utf-8");
- PrintWriter out = response.getWriter();
- out.print(callback + "(" + res.toString() + ")");
- out.flush();
- out.close();
- return null;
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。