加载JSON-P时可以避免使用全局回调函数吗? [英] Can I avoid using global callback function when loading JSON-P?
问题描述
我想使用JSON-P在我的网页上加载我的Google日历Feed。为了使页面上的主要内容加载更快,我只在加载页面后才将JSON-P的脚本标记注入head标记。 Google Calendar API会返回具有回调功能的脚本,请参阅示例此处。
I want to load my Google Calendar feed on my web page using JSON-P. To make the main content on the page load quicker, I inject the script tag for JSON-P into the head tag only after page is loaded. Google Calendar API returns a script with callback function, see example here.
是否可以避免使用全局函数作为回调函数?我想包装所有必要的代码,用于注入标记并在一个包装函数中解析结果。
Is it possible to avoid using global function as a callback function? I would like to wrap all the necessary code for injecting the tag and parsing the results inside one wrapper function.
推荐答案
否。当您使用JSON-P调用时,服务器返回如下内容:
No. When you are using JSON-P calls, the server returns something like below:
callback({...})
使用< script>
元素后引用这个JSON-P调用URL,浏览器将下载JavaScript代码并执行它,这意味着使用服务器提供的数据执行回调
函数。
After you use <script>
element to reference this JSON-P call URL, browser will download the JavaScript code and execute it, which means to execute your callback
function using server-provided data.
如果您不希望回调函数污染您的全局命名空间,只需在回调函数中添加一些命名空间,如 com.mycode.callback
。
If you don't want callback function to pollute your global namespace, just add some namespace to your callback function, like com.mycode.callback
.
使用JSON-P的最大优点是它可以解决同源策略,您可以轻松使用其他域中的数据。
The biggest advantage of using JSON-P is that it can work around Same Origin Policy in browser and you can easily use data from other domains.
这篇关于加载JSON-P时可以避免使用全局回调函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!