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)  編輯  收藏


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


          網站導航:
           

          導航

          統計

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 府谷县| 禹城市| 嘉荫县| 冷水江市| 庆元县| 呼玛县| 中西区| 虹口区| 平昌县| 赣榆县| 舞钢市| 临高县| 玉溪市| 元江| 女性| 乌什县| 邢台县| 屏东县| 察隅县| 临夏市| 原平市| 西城区| 越西县| 伊吾县| 长顺县| 四川省| 勃利县| 和硕县| 浦江县| 防城港市| 弋阳县| 都兰县| 宁明县| 阿瓦提县| 安丘市| 泸溪县| 渭源县| 灵石县| 阳谷县| 四会市| 申扎县|