File tree Expand file tree Collapse file tree 1 file changed +17
-5
lines changed Expand file tree Collapse file tree 1 file changed +17
-5
lines changed Original file line number Diff line number Diff line change @@ -304,16 +304,28 @@ window.onmessage = function(e) {
304
304
305
305
### JSONP
306
306
307
- JSONP 是服务器与客户端跨源通信的常用方法。最大特点就是简单适用 ,老式浏览器全部支持,服务端改造非常小。
307
+ JSONP 是服务器与客户端跨源通信的常用方法。最大特点就是简单易用,没有兼容性问题 ,老式浏览器全部支持,服务端改造非常小。
308
308
309
- 它的基本思想是,网页通过添加一个 ` <script> ` 元素,向服务器请求 JSON 数据,这种做法不受同源政策限制;服务器收到请求后,将数据放在一个指定名字的回调函数里传回来 。
309
+ 它的做法如下 。
310
310
311
- 首先,网页动态插入` <script> ` 元素,由它向跨源网址发出请求。
311
+ 第一步,网页添加一个` <script> ` 元素,向服务器请求一个脚本,这不受同源政策限制,可以跨域请求。
312
+
313
+ ``` html
314
+ <script src =" http://api.foo.com?callback=bar" ></script >
315
+ ```
316
+
317
+ 注意,请求的脚本网址有一个` callback ` 参数(` ?callback=bar ` ),用来告诉服务器,客户端的回调函数名称(` bar ` )。
318
+
319
+ 第二步,服务器收到请求后,拼接一个字符串,将 JSON 数据放在函数名里面,作为字符串返回(` bar({...}) ` )。
320
+
321
+ 第三步,客户端会将服务器返回的字符串,作为代码解析,因为浏览器认为,这是` <script> ` 标签请求的脚本内容。这时,客户端只要定义了` bar() ` 函数,就能在该函数体内,拿到服务器返回的 JSON 数据。
322
+
323
+ 下面看一个实例。首先,网页动态插入` <script> ` 元素,由它向跨域网址发出请求。
312
324
313
325
``` javascript
314
326
function addScriptTag (src ) {
315
327
var script = document .createElement (' script' );
316
- script .setAttribute (" type" , " text/javascript" );
328
+ script .setAttribute (' type' , ' text/javascript' );
317
329
script .src = src;
318
330
document .body .appendChild (script);
319
331
}
@@ -333,7 +345,7 @@ function foo(data) {
333
345
334
346
``` javascript
335
347
foo ({
336
- " ip " : " 8.8.8.8"
348
+ ' ip ' : ' 8.8.8.8'
337
349
});
338
350
```
339
351
You can’t perform that action at this time.
0 commit comments