将 .ajax() 与 JSONP 一起使用的基本示例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5943630/
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
Basic example of using .ajax() with JSONP?
提问by simon
Please could someone help me work out how to get started with JSONP?
请有人帮我弄清楚如何开始使用 JSONP?
Code:
代码:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
var photos = function (data) {
alert(data);
};
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: false,
});
});
Fiddle: http://jsfiddle.net/R7EPt/6/
小提琴:http: //jsfiddle.net/R7EPt/6/
Should produce an alert, as far as I can work out from the documentation: isn't (but isn't producing any errors either).
就我可以从文档中得出的结论而言,应该产生警报:不是(但也不会产生任何错误)。
thanks.
谢谢。
回答by ThatGuy
JSONPis really a simply trick to overcome XMLHttpRequestsame domain policy. (As you know one cannot send AJAX (XMLHttpRequest)request to a different domain.)
JSONP确实是克服XMLHttpRequest相同域策略的简单技巧。(如您所知,不能将AJAX (XMLHttpRequest)请求发送到不同的域。)
So - instead of using XMLHttpRequestwe have to use scriptHTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?
所以 -我们必须使用脚本HTMLl 标签而不是使用XMLHttpRequest,您通常使用这些标签来加载 JS 文件,以便 JS 从另一个域获取数据。听起来怪怪的?
Thing is - turns out scripttags can be used in a fashion similar to XMLHttpRequest! Check this out:
事实是 -脚本标签可以以类似于XMLHttpRequest的方式使用!看一下这个:
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";
You will end up with a scriptsegment that looks like this after it loads the data:
加载数据后,您将得到一个如下所示的脚本段:
<script>
{['some string 1', 'some data', 'whatever data']}
</script>
However this is a bit inconvenient, because we have to fetch this array from scripttag. So JSONPcreators decided that this will work better (and it is):
然而这有点不方便,因为我们必须从脚本标签中获取这个数组。所以JSONP创建者决定这会更好地工作(而且确实如此):
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";
Notice my_callbackfunction over there? So - when JSONPserver receives your request and finds callback parameter - instead of returning plain JS array it'll return this:
注意到那边的 my_callback函数了吗?所以 - 当JSONP服务器收到您的请求并找到回调参数时 - 它不会返回普通的 JS 数组,而是返回:
my_callback({['some string 1', 'some data', 'whatever data']});
See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about JSONP: it's a callback and script tags.
看看利润在哪里:现在我们得到了自动回调(my_callback),一旦我们获得数据就会触发它。这就是关于JSONP的全部知识:它是一个回调和脚本标签。
NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.
注意:
这些是 JSONP 用法的简单示例,这些不是生产就绪脚本。
RAW JavaScript demonstration (simple Twitter feed using JSONP):
RAW JavaScript 演示(使用 JSONP 的简单 Twitter 提要):
<html>
<head>
</head>
<body>
<div id = 'twitterFeed'></div>
<script>
function myCallback(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
document.getElementById('twitterFeed').innerHTML = text;
}
</script>
<script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
</body>
</html>
Basic jQuery example (simple Twitter feed using JSONP):
基本 jQuery 示例(使用 JSONP 的简单 Twitter 提要):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
$('#twitterFeed').html(text);
}
});
})
</script>
</head>
<body>
<div id = 'twitterFeed'></div>
</body>
</html>
JSONPstands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)
JSONP代表带 Padding 的 JSON。(非常糟糕的技术,因为它实际上与大多数人认为的“填充”无关。)
回答by Petr Peller
There is even easier way how to work with JSONP using jQuery
使用 jQuery 处理 JSONP 有更简单的方法
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The ?on the end of the URL tells jQuery that it is a JSONP request instead of JSON. jQuery registers and calls the callback function automatically.
在?该URL的末尾告诉jQuery的,这是一个JSONP请求而不是JSON。jQuery 会自动注册并调用回调函数。
For more detail refer to the jQuery.getJSON documentation.
有关更多详细信息,请参阅jQuery.getJSON 文档。
回答by PapaFreud
In response to the OP, there are two problems with your code: you need to set jsonp='callback', and adding in a callback function in a variable like you did does not seem to work.
针对 OP,您的代码存在两个问题:您需要设置 jsonp='callback',并且像您一样在变量中添加回调函数似乎不起作用。
Update: when I wrote this the Twitter API was just open, but they changed it and it now requires authentication. I changed the second example to a working (2014Q1) example, but now using github.
更新:当我写这篇文章时,Twitter API 刚刚打开,但他们改变了它,现在需要身份验证。我将第二个示例更改为工作(2014Q1)示例,但现在使用 github。
This does not work any more - as an exercise, see if you can replace it with the Github API:
这不再起作用了——作为练习,看看你是否可以用 Github API 替换它:
$('document').ready(function() {
var pm_url = 'http://twitter.com/status';
pm_url += '/user_timeline/stephenfry.json';
pm_url += '?count=10&callback=photos';
$.ajax({
url: pm_url,
dataType: 'jsonp',
jsonpCallback: 'photos',
jsonp: 'callback',
});
});
function photos (data) {
alert(data);
console.log(data);
};
although alert()ing an array like that does not really work well... The "Net" tab in Firebug will show you the JSON properly. Another handy trick is doing
尽管警报()这样的数组并不能很好地工作...... Firebug 中的“网络”选项卡将正确显示 JSON。另一个方便的技巧是做
alert(JSON.stringify(data));
You can also use the jQuery.getJSONmethod. Here's a complete html example that gets a list of "gists" from github. This way it creates a randomly named callback function for you, that's the final "callback=?" in the url.
您还可以使用jQuery.getJSON方法。这是一个完整的 html 示例,它从 github 获取“要点”列表。这样它会为您创建一个随机命名的回调函数,这就是最终的“callback=?” 在网址中。
<!DOCTYPE html>
<html lang="en">
<head>
<title>JQuery (cross-domain) JSONP Twitter example</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('https://api.github.com/gists?callback=?', function(response){
$.each(response.data, function(i, gist){
$('#gists').append('<li>' + gist.user.login + " (<a href='" + gist.html_url + "'>" +
(gist.description == "" ? "undescribed" : gist.description) + '</a>)</li>');
});
});
});
</script>
</head>
<body>
<ul id="gists"></ul>
</body>
</html>
回答by Ganesh Babu
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
});
});</script>
</body>
</html>
The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here
上面的代码有助于从 Flicker API 获取图像。这使用 GET 方法使用 JSONP 获取图像。可以在这里找到详细信息

