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 楊軍威 閱讀(200) 評論(0)  編輯  收藏


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


          網站導航:
           

          導航

          統計

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 仙居县| 伊吾县| 邵东县| 浦东新区| 奈曼旗| 响水县| 扶风县| 新邵县| 山阳县| 石嘴山市| 理塘县| 吴桥县| 胶州市| 兖州市| 平塘县| 西乡县| 宁强县| 浪卡子县| 六枝特区| 威宁| 旅游| 荔波县| 潼关县| 百色市| 亳州市| 灯塔市| 中西区| 广宁县| 台前县| 通辽市| 象州县| 焉耆| 高雄县| 商城县| 阿拉善右旗| 两当县| 西乌珠穆沁旗| 安福县| 确山县| 澄迈县| 甘泉县|