ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## JSONP 网页通过添加一个`<script>`元素,向服务器请求 JSON 数据,这种做法不受同源政策限制 ``` function addScriptTag(src) { var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.src = src; document.body.appendChild(script); } window.onload = function () { addScriptTag('http://example.com/ip?callback=foo'); } function foo(data) { console.log('Your public IP address is: ' + data.ip); }; ``` ## CORS 通信 CORS 请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。 简单请求 1. 请求方法 * HEAD * GET * POST 2. http 头信息 * Accept * Accept-Language * Content-Language * Last-Event-ID * Content-Type:只限于三个值`application/x-www-form-urlencoded`、`multipart/form-data`、`text/plain` 凡是不同时满足上面两个条件,就属于非简单请求 ### Access-Control- 开头 #### Access-Control-Allow-Origin 愿意接受的域名 必填字段 ##### Access-Control-Allow-Credentials cookie 是否包含在请求中 布尔值 默认为`false` 只有需要发送cookie 时,在设置`true` 需要同时 开启`withCredentials` ``` var xhr = new XMLHttpRequest(); xhr.withCredentials = true; ``` #### Access-Control-Expose-Headers 该字段可选。CORS 请求时,`XMLHttpRequest`对象的`getResponseHeader()`方法只能拿到6个服务器返回的基本字段:`Cache-Control`、`Content-Language`、`Content-Type`、`Expires`、`Last-Modified`、`Pragma`。如果想拿到其他字段,就必须在`Access-Control-Expose-Headers`里面指定。上面的例子指定,`getResponseHeader('FooBar')`可以返回`FooBar`字段的值。