直接上代码:
js:
<html> <head> <title>JSONP</title> </head> <script src = "jquery.js"></script> <script> $(function(){ $.ajax({ type:'POST', url : 'http://mainsite.service.com:8090/article/get/by/typeid', dataType : 'jsonp', data:{"siteid":0,"tagid":0,"page":1,"size":2,"jsonpCallback":"callback"}, jsonpCallback: 'callback', success : function() { //do something... }, error : function(data) { //do something... } }); }) function callback(data){ var jsonobj = eval('(' + data + ')'); alert(jsonobj.name); } </script> <body> </body> </html>
后端代码:
@RequestMapping(value = "/get/by/typeid" ,method=RequestMethod.GET, produces = "application/json;charset=utf-8" ) @ResponseBody public void getArticles_post(HttpServletResponse resp, HttpServletRequest req) throws TException { PrintWriter pWriter = null; try { String callback = req.getParameter("jsonpCallback"); pWriter = resp.getWriter(); //json数据 String json = "{"name":"chopper","sex":"man"}"; pWriter.write(callback+"('"+json+"')"); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ if(pWriter!=null){ pWriter.flush(); pWriter.close(); } } }