jsonp 实现跨域例子
Posted Hendsame
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jsonp 实现跨域例子相关的知识,希望对你有一定的参考价值。
直接上代码:
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(); } } }
以上是关于jsonp 实现跨域例子的主要内容,如果未能解决你的问题,请参考以下文章