页面(原生JS)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSONP DEMO</title> <script type="text/javascript"> var flightDataHandler = function(data) { alert("您查询的航班结果:票价:" + data.price + ",余票:" + data.tickets + "张"); } var script = document.createElement("script"); script.setAttribute("src","http://localhost:8080/rapiddemo/jsonp/tickets?code=SZ1988&callback=flightDataHandler"); document.getElementsByTagName('head')[0].appendChild(script); </script> </head> <body> </body> </html>
jQuery版本:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSONP DEMO</title> <script type="text/javascript" src="/rapiddemo/scripts/jquery.js"></script> <script type="text/javascript"> $(function() { $.ajax({ type:"GET",url:"http://localhost:8080/rapiddemo/jsonp/tickets",data:{ code:'SZ1988' },dataType:"jsonp",jsonp:"callback",jsonpCallback:"flightDataHandler",success:function(data) { console.info('query success'); alert("您查询的航班结果:票价:" + data.price + ",余票:" + data.tickets + "张"); },error:function() { alert("jquery Ajax error!"); } }); }); </script> </head> <body> </body> </html>
spring controller代码:
package com.company.project.controller; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javacommon.base.BaseRestSpringController; @Controller @RequestMapping(value="/jsonp/") public class JsonpController extends BaseRestSpringController<Object,Long>{ private static Logger logger = Logger.getLogger(JsonpController.class); @RequestMapping(value="tickets") public String tickets(@RequestParam("code") String code,@RequestParam("callback") String callback,HttpServletResponse response) throws IOException { logger.info("code:" + code); logger.info("callback:" + callback); String scs = ""+callback+"({'code':'SZ1988','price':842,'tickets':29})"; response.getWriter().println(scs); logger.info("method called success..."); return null; } }
关于jsonp,请参考http://q.115.com/t-158587-1211997.html