1. 程式人生 > >JQueryAjax+SpringMVC跨域請求(轉)

JQueryAjax+SpringMVC跨域請求(轉)

jquery.min.js:4 Cross-Origin Read Blocking (CORB) blocked cross-origin 

跨域:瀏覽器對於javascript的同源策略的限制,例如a.cn下面的js不能呼叫b.cn中的js,物件或資料(因為a.cn和b.cn是不同域),所以跨域就出現了.

參考:https://blog.csdn.net/xuhonglei_2004/article/details/50137137,https://blog.csdn.net/lcore/article/details/41022567,https://blog.csdn.net/u014727260/article/details/72793459

http://www.cnblogs.com/chopper/archive/2012/03/24/2403945.html 這個原理解釋的清楚

頁面端寫為: Js程式碼  

var params = "18";
$.ajax({
    type: "GET",  //提交方式
    url: "http://192.168.33.110:8789/region/getDataByIdcallback/" + params,//路徑
    cache :false,
    // jsonp: "callback",
    jsonpCallback:"callback",  //callback要與後臺對應
    dataType: 'JSONP',  // 處理Ajax跨域問題
    success: function (result) {//返回資料根據結果進行相應的處理
        console.log('result', result);
    }
});


後端寫為: 

@GetMapping("/getDataByIdcallback/{id}")
public String getDataByIdcallback(@PathVariable("id") String id) {
    ResponseResult responseResult = new ResponseResult();
    Map<String, Object> message = new HashMap<>();
    String result = "";
    try {
        Long dataId = Long.parseLong(id);
        Region region = regionRepository.findById(dataId).get();
        message.put("id", region.getId());
        message.put("paraLayers", region.getParaLayers());
        message.put("paraBbox", region.getParaBbox());
        message.put("paraCenter", region.getParaCenter());
        ObjectMapper mapper = new ObjectMapper();
       //也可以用傳參String callbackFunName =req.getParameter("callbackparam");//得到js函式名稱
         //這個拼接是重點。。。callback與前端對應
          result = "callback("+mapper.writeValueAsString(message)+")";
    } catch (Exception e) {
        Map<String, Object> reError = new HashMap<>();
        reError.put("status", "fail");
        reError.put("data", e.getMessage());
        result = reError.toString();
    }
    return result;
}