Open yxfanxiao opened 8 years ago
<script>标签不受同源策略限制
<script>
server以express为例:
router.get("/v1/carousel", (req, res, next) => { const cb = req.query.callback const carousel = [ {index:1, url:"url1"}, {index:2, url:"url2"}] // 拼接 res.send(cb ? `${cb}(${carousel})` : carousel) }) // 每次手动拼有点烦, 找了下, express还包装了jsonp support router.get("/v1/carousel", (req, res, next) => { const carousel = [ {index:1, url:"url1"}, {index:2, url:"url2"}] res.jsonp(carousel) })
client
// jsonp和ajax并不一样, 但是jquery强行封装在了一起 $.ajax({ url: "http://localhost:3000/v1/carousel", dataType: "jsonp" }).done(data => { // data: carousel is here })
手写一个简易实现
const url = "http://localhost:3000/v1/carousel" const callbackName = cb const oS = document.createElement("script") const oHead = document.getElementsByTagName("head")[0] oHead.appendChild(oS) window[callbackName] = json => { oHead.removeCHild(oS) window[callbackName] = null // json: carousel is here } oS.src = `${url}?callback=${callbackName}`
在header中添加 Access-Control-Allow-Origin
router.get("/v1/carousel", (req, res, next) => { const carousel = [ {index:1, url:"url1"}, {index:2, url:"url2"} ] res.set("Access-Control-Allow-Origin", "http://www.foo.com") res.send(carousel)
使用条件:
使用方法: 将符合上述条件页面的document.domain设置为同样的二级域名
主要是用于iframe中,所以这个方法暂且了解一下。
js跨域
JSONP (JSON with Padding) 被"包裹"的JSON
server以express为例:
client
手写一个简易实现
CORS (cross origin resource sharing) 跨域资源共享
在header中添加 Access-Control-Allow-Origin
document.domain
使用条件:
主要是用于iframe中,所以这个方法暂且了解一下。