[TOC]
## 跨域
前端 ajax 訪問時,瀏覽器有同源策略
跨域條件:協議、域名、端口,有一個不同就算跨域
### 可以跨域的三個標簽
1. `<img src> `
3. `<link href=''>`
4. `<srcipt href=''>`
`<img>`用于打點統計,統計網站可能是其他域
`<link>< script>`可以使用CDN,CDN的也是其他域
`< script>`可以用于 JSONP
### JSONP 實現原理
- 加載`http://coding.m.mooc.com/classindex.html`
- 不一定服務器端真正有一個 classindex. htm文件
- 報務器可以根據請求,動態生成一個文件,返回
- 同理于< script src="http;/ coding.m.imooccom/ api.js">
```
<script>
window.callback=function(data){
//這是我們跨域得到的信息
console.log(data)
}
</script>
<script scr='http://coding.m.imooc.com/api.js></script>
<!-- 以上返回 callback({x:100,y:200}) 括號中的 json 可自己更改-->
```
### 通過服務器設置解決跨域
```php
//注意:不同后端語言的寫法可能不一樣
//第二個參數填寫允許跨域的域名稱,不建議直接寫"*k
response. setheader ("access-control-allow-origin","http://a.com,http://bcom")
response. setheader ("access-control-allow-headers","x-requested-with");
response. setheader ("access-control-allow-methods","PUT, POST, GET, DELETE, PTIONS")
//接收跨域的 cookie
response. setheader ("access-control-allow-credentials","true
```