通過jsonp解決瀏覽器跨域問題

來源:互聯網
上載者:User

標籤:

一、什麼是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解決瀏覽器跨域問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.