front-end-interview-handbook/packages/quiz/questions/explain-how-jsonp-works-and.../zh-CN.mdx

30 lines
1.3 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 解释JSONP 如何工作(以及它为什么不是真正的 Ajax)
---
JSONP (JSON with Padding) 是一种通常用来绕过网络浏览器中的跨域策略的方法,因为不允许从当前页面的 Ajax 请求到跨源域。
JSONP 工作方式是通过一个 `<script>` 标签向一个跨源域提出请求,通常使用一个 `callback` 查询参数, 例如:`https://example.com?callback=printData`。 然后,服务器将把数据填充到一个名为 `printData` 的函数中,然后返回给客户端。
```html
<!-- https://mydomain.com -->
<script>
function printData(data) {
console.log(`My name is ${data.name}!`);
}
</script>
<script src="https://example.com?callback=printData"></script>
```
```js
// 从 https://example.com?callback=printData 加载的文件
printData({ name: 'John Doe' });
```
客户端必须将`printData`函数设在其全局范围内,当收到跨源域的响应时,该函数将由客户端执行。
JSONP 可能是不安全的,并涉及一些安全问题。 因为 JSONP 真的是 JavaScript它可以做所有其它 JavaScript 可以做的事情,所以你需要信任 JSONP 数据的提供者。
这几天, [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) 是推荐的方法JSONP 被视为一种 hack破解