我正在我的博客上添加最近的视频小工具。在那个小部件中我应该添加这一行
<script src="/feeds/posts/default?orderby=published&alt=json-in-script&callback=showrecentpostswiththumbs">
此外,我还添加了另一个脚本,该脚本具有方法 showrecentpostswiththumbs [用于回调]。请让我知道上面的语法有什么作用?
编辑 在主的评论之后:)
实际上,我的博客托管在 blogspot.com 上。因此,从这个 Angular 来看,如果您将 /feeds/posts/default?orderby=published&alt=json-in-script 附加到任何博客网址,它将生成一些代码。我只是想知道它有什么作用?以及回调参数中使用的方法会发生什么[无论回调方法的定义是什么:)]。
例如: http://googleblog.blogspot.com /feeds/posts/default?orderby=published&alt=json-in-script
最佳答案
仅从您发布的内容中无法判断,但 URL 中的参数命名表明 JSONP .
JSONP 的基础是通过将裸 JSON 对象包装在函数调用中来允许跨域 AJAX 调用,以便结果可以作为脚本执行。
JSON 代码:
function getJSON(url) {
var xhr = new XHR(url); // pseudocode
xhr.onsuccess = callback;
xhr.send();
}
function callback(data) {}
JSON 响应:
{ "items" : [1, 5, 7] }
等效 JSONP 代码:
function getJSONP(url) {
var script = document.createElement("script");
script.src = url + "&callback=callback");
script.type = "text/javascript";
document.body.appendChild(script);
}
function callback(data) {}
JSONP 响应:
callback({ "items" : [1, 5, 7] })
编辑
它是 JSONP。比较以下三个请求的结果:
- http://googleblog.blogspot.com/feeds/posts/default?orderby=published&alt=json
- http://googleblog.blogspot.com/feeds/posts/default?orderby=published&alt=json-in-script
- http://googleblog.blogspot.com/feeds/posts/default?orderby=published&alt=json-in-script&callback=showrecentpostswiththumbs
第一个以原始 JSON 形式返回提要,第二个以带有默认回调名称的 JSONP 形式返回,第三个使用为回调函数提供的名称以 JSONP 形式返回。
关于javascript - 这个 JavaScript 的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2587228/