jsonp 与 jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2681466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:02:11  来源:igfitidea点击:

jsonp with jquery

jqueryajaxjsonp

提问by akula1001

Can you give a very simple example of reading a jsonp request with jquery? I just can't get it to work.

你能举一个用jquery读取jsonp请求的非常简单的例子吗?我只是无法让它工作。

回答by Tomas Sedovic

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 getJSONfunction 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.

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

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

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