1、 http://hanqunfeng.iteye.com/blog/1866712
2、 http://blog.csdn.net/z69183787/article/details/15808921
3、 http://www.cnblogs.com/JerryTian/p/4194900.html
4、 http://feitianbenyue.iteye.com/blog/2046877
一 程序所需jar文件及POM
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.6</version> </dependency>
二 后台代码编写
try { response.setContentType("text/plain"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); Map<String,String> map = new HashMap<String,String>(); map.put("result", "content"); PrintWriter out = response.getWriter(); JSONObject resultJSON = JSONObject.fromObject(map); //根据需要拼装json String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数 out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据 out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); }
三 JS代码编写
$.ajax({ type : "get", async:false, url : "http://app.example.com/base/json.do?sid=1494&busiId=101", dataType : "jsonp",//数据类型为jsonp jsonp: "jsonpCallback",//服务端用于接收callback调用的function名的参数 success : function(data){ $("#showcontent").text("Result:"+data.result) }, error:function(){ alert('fail'); } });
四 相关错误
java.lang.ClassCastException: JSON keys must be strings
解决如下:
JsonConfig jsonConfig = new JsonConfig(); // 排除,避免循环引用 There is a cycle in the hierarchy! jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); jsonConfig.setIgnoreDefaultExcludes(true); jsonConfig.setAllowNonStringKeys(true); if (Validator.isNotNullOrEmpty(excludes)){ jsonConfig.setExcludes(excludes); } String string = JsonUtil.toJSON(obj, jsonConfig).toString(4, 4);
五 相关说明
jsonp
类型:String
在一个 jsonp 请求中重写回调函数的名字。这个值用来替代在 "callback=?" 这种 GET 或 POST 请求中 URL 参数里的 "callback" 部分,比如 {jsonp:'onJsonPLoad'} 会导致将 "onJsonPLoad=?" 传给服务器。
jsonpCallback
类型:String
为 jsonp 请求指定一个回调函数名。这个值将用来取代 jQuery 自动生成的随机函数名。这主要用来让 jQuery 生成度独特的函数名,这样管理请求更容易,也能方便地提供回调函数和错误处理。你也可以在想让浏览器缓存 GET 请求的时候,指定这个回调函数名。