JSONP 和 XMLHttpRequest 问题
我试图了解浏览器(以及 Javascript 新手)中的同源策略,并遇到了维基百科上的 JSONP 页面。 如何工作部分说 -
现在,考虑可以指定任何 URL,包括返回 JSON 的 URL,因为 src >元素的属性。这意味着可以通过 > 中的脚本元素检索 JSON。 HTML 页面。
但是,JSON 文档不是 JavaScript 程序。如果要由浏览器在元素中求值,则 src URL 的返回值必须是可执行的 JavaScript。在 JSONP 使用模式中,URL 返回动态生成的 JSON,并包含一个函数调用。这是 JSONP 的“填充”(有时是“前缀”)。
我的问题是 -
- 那么 XMLHTTPRequest() 应该只返回 javascript 或 html 吗?不能返回纯json文档吗?
- 我认为同源策略不适用于 XMLHttpRequest() 调用。为什么需要在 DOM 中注入标签来调用第三方服务器?这就是网站上所有广告附加组件打电话回家收集数据的方式吗?
- 到最后我根本就不懂JSONP。有人可以解释一下或请我参考更好的解释吗?
谢谢,
-P
Am trying to understand the same origin policy in browsers (and also Javascript newbie) and ran into the JSONP page on wikipedia. The How It Works section says -
Now, consider that it is possible to specify any URL, including a URL that returns JSON, as the src > attribute for a element. This means it is possible to retrieve JSON via a script element in > an HTML page.
However, a JSON document is not a JavaScript program. If it is to be evaluated by the browser in a element, the return value from the src URL must be executable JavaScript. In the JSONP usage pattern, the URL returns the dynamically-generated JSON, with a function call wrapped around it. This is the "padding" (or sometimes, "prefix") of JSONP.
My questions are -
- So is XMLHTTPRequest() supposed to return only javascript or html? Can it not return a pure json document?
- I thought the same origin policy does not apply to XMLHttpRequest() call. Why is there a need to inject a tag into the DOM to make a call to a third party server? Is that how all the advertising add-ons to sites call home to collect data?
- At the end of it I did not understand JSONP at all. Can some one explain or refer me to a better explanation please?
Thanks,
- P
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它可以返回您喜欢的任何文本(也许是二进制数据,但我从未见过这样的尝试,所以我不会发誓)
可以。
同源政策绝对确实适用于 XHR
通过从另一个源加载脚本(带有嵌入数据)可以绕过同源策略。
这是因为您没有使用 JavaScript 读取远程资源。您正在执行一些带有嵌入数据的远程 JavaScript。
JSON-P 只是从另一个来源加载一些 JavaScript。该 JavaScript 由单个函数调用(对您在添加
元素之前定义的函数)和单个参数(JS 对象或数组文字)组成。
It can return any text you like (and maybe binary data, but I've never see that tried so I won't swear to it)
It can.
The same origin policy most definitely does apply to XHR
The same origin policy is bypassed by loading a script (with embedded data) from another origin.
This is because you aren't reading a remote resource using JavaScript. You are executing some remote JavaScript which comes with embedded data.
JSON-P is just loading some JavaScript from another origin. That JavaScript consists of a single function call (to a function you define before adding the
<script>
element) with a single argument (a JS object or array literal).