Skip to content

Instantly share code, notes, and snippets.

@svaponi
Created June 1, 2015 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svaponi/e94764a5e4cece52bd0c to your computer and use it in GitHub Desktop.
Save svaponi/e94764a5e4cece52bd0c to your computer and use it in GitHub Desktop.
JSONP example with native Javascript and with JQuery
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<title>JS Bin - CNJ Recent posts</title>
<script type="text/javascript" charset="utf-8">
//Se non metto callback=? il metodo jquery fa una chiamata ajax!!
var cnjRecentPosts = 'http://www.cosenonjaviste.it/api/get_recent_posts?callback=?';
$(document).ready(function() {
$.getJSON(cnjRecentPosts, function(data) {
//alert("I post recenti sono "+ data.count);
$('<ul></ul>').appendTo('#recent_posts');
$('<h3>Raw JSON Content:</h3>').appendTo('#recent_posts');
$(data.posts).each(function(i, el) {
$('#recent_posts ul').append('<li><a href="' + el.url + '" target="_blank">' + el.title + '</a></li>');
});
});
});
</script>
</head>
<body>
<script type="text/javascript">
function recentPosts(data) {
document.write("<h3>I post recenti sono "+ data.count + ", eccoli..</h3>");
document.write("<div id=\"recent_posts\"></div>");
document.write("<pre>");
printData(data, 0);
document.write("</pre>");
}
function printData(data, nTab) {
for (var i in data) {
if (typeof data[i] == 'object') {
document.write(tab(nTab) + i + " is an OBJECT\n");
printData(data[i], nTab+1);
} else {
document.write(tab(nTab) + i + " (" + typeof data[i] + "): " + data[i] + "\n");
}
}
}
function tab(n) {
var str = '';
var N = (n ? n : 0);
for (var i = 0; i < N; i++)
str += (N-i==1) ? '+\t' : '\t';
return str;
}
//recentPosts([0,1,2,3,4,5]);
</script>
<script type="text/javascript" src="http://www.cosenonjaviste.it/api/get_recent_posts?callback=recentPosts">
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment