jsonp 与 jquery

发布于 2024-08-29 07:38:06 字数 1563 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故笙诉离歌 2024-09-05 07:38:06

以下是有效示例:

<html><head><title>Twitter 2.0</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head><body>
<div id='tweet-list'></div>
<script type="text/javascript">
$(document).ready(function() {
    var url =  "http://api.twitter.com/1/statuses/user_timeline/codinghorror.json";
    $.getJSON(url + "?callback=?", null, function(tweets) {
        for(i in tweets) {
            tweet = tweets[i];
            $("#tweet-list").append(tweet.text + "<hr />");
        }
    });
});
</script>
</body></html>

请注意请求 URL 末尾的 ?callback=?。这向 getJSON 函数表明我们要使用 JSONP。删除它,将使用普通 JSON 请求。由于同源政策,这将失败。

您可以在 JQuery 站点上找到更多信息和示例:http://api.jquery.com/jQuery。获取JSON/

Here is working example:

<html><head><title>Twitter 2.0</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head><body>
<div id='tweet-list'></div>
<script type="text/javascript">
$(document).ready(function() {
    var url =  "http://api.twitter.com/1/statuses/user_timeline/codinghorror.json";
    $.getJSON(url + "?callback=?", null, function(tweets) {
        for(i in tweets) {
            tweet = tweets[i];
            $("#tweet-list").append(tweet.text + "<hr />");
        }
    });
});
</script>
</body></html>

Notice the ?callback=? at the end of the requested URL. That indicates to the getJSON function that we want to use JSONP. Remove it and a vanilla JSON request will be used. Which will fail due to the same origin policy.

You can find more information and examples on the JQuery site: http://api.jquery.com/jQuery.getJSON/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文