Spring Boot支援JSONP跨域請求資料(Ajax的jsonp)
阿新 • • 發佈:2019-01-23
1:在Spring Boot的Api伺服器上進行配置
package me.loveshare.note1.configuration; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice; /** * Created by Tony on 2017/8/1. * Spring Boot支援跨域請求的JSONP資料. */ @ControllerAdvice(basePackages = {"me.loveshare.note1.api"}) public class JSONPConfiguration extends AbstractJsonpResponseBodyAdvice { public JSONPConfiguration() { super("callback", "jsonp"); } }
2:Jsonp測試
2.1:測試api介面配置
package me.loveshare.note1.api; import lombok.extern.slf4j.Slf4j; import me.loveshare.note1.data.entity.bo.common.JsonResult; import me.loveshare.note1.data.entity.bo.common.JsonResultMethod; import me.loveshare.note1.data.utils.DateUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.Date; /** * Created by Tony on 2017/8/4. */ @Slf4j @RestController public class TestDataApi extends BaseApi { /** * json資料測試 */ @RequestMapping(value = "test", produces = "application/json; charset=UTF-8", method = {RequestMethod.GET, RequestMethod.POST}) public JsonResult initDbDatasC() { return JsonResultMethod.code_200("The request completed successfully.", DateUtils.timestamp(new Date())); } }
{"code":200,"message":"The request completed successfully.","data":"2017-08-11 17:55:33:248"}
/**/myFunc({"code":200,"message":"The request completed successfully.","data":"2017-08-11 17:55:52:774"});
3:前段web的部分js的ajax請求程式碼:
function jsonpTestFunc() { var req_data = {"pageIndex": 1, "pageSize": 5}; if (lock_req) return false; lock_req = true; $.ajax({ url: "http://192.168.1.119:5201/note1/userinfo/list.json?time=" + Date.parse(new Date()), type: "POST", data: req_data, dataType: "jsonp", //返回JSONP格式的資料,此值固定 jsonp: "callback", //回撥函式的名字,此值固定 timeout: 30000, success: function (data) { console.log(JSON.stringify(data)); lock_req = false; }, error: function () { lock_req = false; } }); }
伺服器請求日誌:
User-Access-Args:{"protocol":"HTTP/1.1(http)","ip":"192.168.2.152","port":"49985","method":"GET","url":"/note1/userinfo/list.json?time=1502508020000&callback=jQuery32105595664549758419_1502508020161&pageIndex=1&pageSize=5&_=1502508020162","user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36","uAT":"null"}