JSONP實現跨域
背景分析
瀏覽器出於安全考慮,制定了同源策略。(位於 server1.example.com 的網頁無法與不是 server1.example.com的服務器溝通)
概述
JSONP(JSON with Padding)是JSON的一種“使用模式”,可用於解決主流瀏覽器的跨域數據訪問的問題。
原理
利用javaScript中的src屬性實現遠程數據的獲取(src不受同源限制), 獲取的數據是一個JS對象,由瀏覽器負責解析JS。
<script type="text/javascript" src="http://manage.jt.com/test.json"></script>
實現
頁面請求,JS代碼。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSONP測試</title>
<script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
alert("測試訪問開始!!!!!")
$.ajax({
url:"http://manage.jt.com/web/testJSONP",
type:"get", //jsonp只能支持get請求
dataType:"jsonp", //dataType表示返回值類型
//jsonp: "callback", //指定參數名稱
//jsonpCallback: "hello", //指定回調函數名稱
success:function (data){ //data經過jQuery封裝返回就是json串
alert(data.id);
alert(data.name);
alert(data.itemId);
alert(data.itemDesc);
//轉化為字符串使用
//var obj = eval("("+data+")");
//alert(obj.name); }
});
})
</script>
</head>
<body>
<h1>JSON跨域請求測試</h1>
</body>
</html>
服務器處理
package com.jt.web.controller;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.ItemDesc;
import com.jt.util.ObjectMapperUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/web/")
public class JSONPController {
/**
* 完成jsonp跨域訪問
* url: http://manage.jt.com/web/testJSONP?callback=jQuery111104808002072562081_1610519800035&_=1610519800036
* 參數:callback=jQuxxxx
* 返回值:callback(JSON)
*/
public String jsonp(String callback){
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(101l).setItemDesc("跨域訪問");
String json = ObjectMapperUtil.toJson(itemDesc);
return callback+"("+json+")";
}
/**
* * 關於JSONPObject的説明,主要需要自己對json類型數據進行轉換.
*/ @RequestMapping("testJSONP")
public JSONPObject jsonp1(String callback){
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(101l).setItemDesc("跨域訪問");
return new JSONPObject(callback, itemDesc);
}
}
CORS方式
跨域資源共享(英語:Cross-origin resource sharing,縮寫:CORS),用於讓網頁的受限資源能夠被其他域名的頁面訪問的一種機制。(實現跨域),CORS通過在響應頭中標識允許跨域的網址.之後同源策略基於安全性的規範予以放行的一種跨域訪問方式.
説明:需要在服務器中添加允許訪問的標識即可.
package com.jt.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class COUSConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")//什麼樣的請求允許跨域
.allowedOrigins("http://www.jt.com","*")//允許通過的路徑
.allowedMethods("*")//允許什麼樣的請求方式
.allowCredentials(true)//是否允許攜帶cookie
.maxAge(10*60);//設置跨域通信允許最大時長,默認為30*60s
}
}