前端用用jsonp的方式解決跨域問題
前端用用jsonp的方式解決跨域問題
- 前端用用jsonp的方式解決跨域問題
- 限制與缺點:
- 前端
- 后端
- 測試使用示例
限制與缺點:
不安全、只能使用get方式、后臺需要相應jsonp方式的傳參
前端
function jsonp(obj) {// 動態生成唯一的函數名var fnName = 'jsonp_' + Math.random().toString().replace('.', '');// 創建一個script標簽var script = document.createElement('script');// 定義全局函數window[fnName] = function (res) {try {obj.success(res);} finally {// 移除 script 標簽document.head.removeChild(script);// 刪除全局函數delete window[fnName];}};// 構建請求參數var params = {callback: fnName,invoiceno: obj.data.invoiceno,pk_subjcode: obj.data.pk_subjcode,pk_org: obj.data.pk_org,begindate: obj.data.begindate,enddate: obj.data.enddate,billno: obj.data.billno,pk_supplier: obj.data.pk_supplier};// 將參數對象轉換為查詢字符串var queryString = Object.keys(params).map(function (key) {return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);}).join('&');// 改變 src,添加到 head 中script.src = obj.url + '?' + queryString;// 處理錯誤情況script.onerror = function () {// 移除 script 標簽document.head.removeChild(script);// 刪除全局函數delete window[fnName];if (obj.error) {obj.error(new Error('JSONP 請求失敗'));}};// 把 script 標簽添加到 head 標簽中,就會發送 src 的請求了document.head.appendChild(script);
}
后端
@GetMapping("/getGylPrepayData")public String getGylPrepayData(@RequestParam(value = "callback", defaultValue = "callback") String callback,@RequestParam(value = "pk_group") String pk_group,@RequestParam(value = "pk_org") String pk_org,@RequestParam(value = "begindate") String begindate,@RequestParam(value = "enddate") String enddate,@RequestParam(value = "billno") String billno,@RequestParam(value = "pk_supplier") String pk_supplier) {Map<String, Object> requestBody=new HashMap<>();requestBody.put("pk_group", pk_group);requestBody.put("pk_org", pk_org);requestBody.put("begindate", begindate);requestBody.put("enddate", enddate);requestBody.put("billno", billno);requestBody.put("pk_supplier", pk_supplier);log.info("getGylPrepayData receive request:{}", requestBody);JSONObject response = seaNccGylDataService.getGylPrepayData(requestBody);log.info("getGylPrepayData return response status:{}", response.getString("status"));return callback + "(" + response + ")";}
測試使用示例
// 測試使用使用示例
jsonp({url: 'ip/api/workflow/seanccgyl/testGet',data: {invoiceno: '123',pk_subjcode: '456',pk_org: '789',begindate: '2024-01-01',enddate: '2024-12-31',billno: 'ABC',pk_supplier: 'DEF'},success: function (res) {console.log(res);},error: function (err) {console.error(err);}
});