java學習

          java學習

           

          使用jQuery和jsonp解決js跨域問題

          客戶端系統js代碼:
          <script type="text/javascript">
          function test(a){
          alert(a.name);
          return a;
          }
          $.ajax({
              url:'http://ip:8090/mobile/test.json?method=test',
              type:'POST', //GET
              async:true,    //或false,是否異步
              data:{
               //   name:'yang',age:25
              },
              timeout:5000,    //超時時間
              dataType:'jsonp',    //返回的數據格式:json/xml/html/script/jsonp/text
              beforeSend:function(xhr){
               
              },
              success:function(data,textStatus,jqXHR){
              },
              error:function(xhr,textStatus){
                 
              },
              complete:function(){
                
              }
          })
          </script>
          服務端系統代碼:
          test({name:'yang',age:25});
          客戶端訪問跨域系統時,傳遞客戶端需要執行的方法名,服務端在查詢出數據后,使用傳遞的方法名封裝成js方法的執行返回,客戶端程序就直接執行此方法。

          springmvc后臺例子,返回jsonp數據代碼
          //第一種字符串返回jsonp格式數據
          @RequestMapping(value="/get/{method}",produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
          @ResponseBody
          public String getUser(@PathVariable String method) {
          User user = userService.selectByPrimaryKey(1);
          Gson gson = new Gson();
          String userJson = gson.toJson(user);
          return method+"("+userJson+")";
          }
          //第二種對象返回jsonp格式數據
          spring版本4.1以上
          @RequestMapping("/gett/{method}")
          @ResponseBody
          public Object gett(@PathVariable String method) {
          User user = userService.selectByPrimaryKey(1);
          MappingJacksonValue mjv =  new MappingJacksonValue(user);
          mjv.setJsonpFunction(method);
          return mjv;
           
          }

          posted on 2017-02-22 15:55 楊軍威 閱讀(201) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          導航

          統計

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 始兴县| 南开区| 安福县| 高雄县| 桂平市| 杭州市| 南郑县| 西平县| 波密县| 宜阳县| 桂平市| 谢通门县| 玛纳斯县| 乌拉特中旗| 宁陵县| 长顺县| 巫山县| 桓台县| 唐河县| 灌云县| 萝北县| 大同市| 福海县| 西林县| 仙居县| 黑龙江省| 疏附县| 龙岩市| 永清县| 招远市| 太保市| 延吉市| 香港 | 腾冲县| 东丰县| 云南省| 建平县| 武胜县| 观塘区| 栖霞市| 高唐县|