標籤:
一、什麼是jsonp
為了便於用戶端使用資料,逐漸形成了一種非正式傳輸協議,人們把它稱作JSONP,該協議的一個要點就是允許使用者傳遞一個callback參數給服務端,然後服務端返回資料時會將這個callback參數作為函數名來包裹住JSON資料,這樣用戶端就可以隨意定製自己的函數來自動處理返回資料了。
二、例子 1、用戶端寫法
這裡借用了前端jquery架構對jsonp的支援
var ajaxUrl = "http://192.168.8.141:9092/project/rest/team/matchResult/1/20/1/1000";function localHandler(data) {console.log("fengshu")console.log(data);}var ajaxParam = {async: false,url: ajaxUrl, type: "GET",dataType: ‘jsonp‘,//非正式跨域傳輸協議jsonp: ‘localHandler‘,success: function (json) {//回調資料在localHandler處理}};$.ajax(ajaxParam); 2、伺服器端寫法
@RequestMapping("/matchResult/{page}/{pageSize}/{type}/{matchId}")public void getMatchResult(HttpServletResponse response, @PathVariable("page") int page,@PathVariable("pageSize") int pageSize, @PathVariable("type") String type,@PathVariable("matchId") String matchId) {EntityList<MatchResult> datas = dddService.getTeamRanks(matchId,type,page,pageSize);ObjectMapper objectMapper = new ObjectMapper();String jsonResult=null;try {jsonResult = objectMapper.writeValueAsString(datas);} catch (JsonGenerationException e1) {e1.printStackTrace();} catch (JsonMappingException e1) {e1.printStackTrace();} catch (IOException e1) {e1.printStackTrace();}PrintWriter out=null;response.setCharacterEncoding("UTF-8");try {out = response.getWriter();} catch (IOException e) {e.printStackTrace();} out.println( "localHandler("+jsonResult + ")"); out.close();}
三、總結
目前在瀏覽器端使用json傳輸資料jsonp傳輸協議是解決跨域問題的首選方案
通過jsonp解決瀏覽器跨域問題