SpringBoot項目開發(二十四):支持跨域請求JSONP

在SpringMVC4.1版本以後,Spring爲我們提供了一個AbstractJsonpResponseBodyAdvice的類用來支持jsonp的數據,SpringBoot接收解析web請求是依賴於SpringMVC,所以也可以繼承此類

代碼如下,添加一個配置類,繼承AbstractJsonpResponseBodyAdvice

@ControllerAdvice(basePackages = "com.lkh.tour.controller")
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {

    public JsonpAdvice() {
        super("callback","jsonp");
    }
}

再寫個測試Controller


@RestController
@RequestMapping("/test")
public class JsonpTestController {
 
    @RequestMapping(value = "/testJsonp",produces = MediaType.APPLICATION_JSON_VALUE)
    public Object testJsonp(){
        Map<String,String> map = new HashMap<>();
        map.put("name","zy");
        map.put("age","26");
        return map ;
    }
}

當發送請求爲:http://localhost:2000/test/testJsonp的時候,結果如下:
在這裏插入圖片描述

當發送請求爲:http://localhost:2000/test/testJsonp?callback=getData,結果如下:
在這裏插入圖片描述

可以看到當我們在請求參數中添加callback參數的時候,返回的數據就是 jsonp 的
當請求參數中不帶callback時,返回的數據是 json 的。可以讓我們方便的靈活運用

再附加一個js的jsonp請求示例

<script type="text/javascript">
    function testJsonp() {
        $.ajax({
            type:'get',
            url:'http://localhost:2000/test/testJsonp',
            dataType:'jsonp',
            jsonp:"callback",
            success:function (data) {
                alert(data);
            },
            error:function (err) {
                alert('出現錯誤了!!!');
            }
        });
    }
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章