我试图在浏览器(以及Javascript新手)中理解相同的原始策略,并且遇到了*上的JSONP页面. How It Works部分说 –
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.
我的问题是 –
>那么XMLHTTPRequest()应该只返回javascript或html吗?它不能返回纯粹的json文档吗?
>我认为相同的源策略不适用于XMLHttpRequest()调用.为什么需要在DOM中注入一个标签来调用第三方服务器?这是所有网站的广告附加组件如何回家收集数据?
>最后,我根本不理解JSONP.有人可以向我解释或推荐一个更好的解释吗?
谢谢,
– P.
解决方法:
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.
相同的原产地政策绝对适用于XHR
Why is there a need to inject a tag into the DOM to make a call to a third party server?
通过从另一个来源加载脚本(带有嵌入数据)来绕过相同的原始策略.
这是因为您没有使用JavaScript读取远程资源.您正在执行一些带有嵌入数据的远程JavaScript.
At the end of it I did not understand JSONP at all. Can some one explain or refer me to a better explanation please?
JSON-P只是从另一个来源加载一些JavaScript. JavaScript包含单个函数调用(对于在添加< script>元素之前定义的函数)和单个参数(JS对象或数组文字).