JSONP Example that really works

The great thing about existing JSONP examples is that they all start by explaining the reasons behind using JSONP and give some JSON example code....... and then simple go, "and here's a twitter example"... "and here's a flicker example".. Great. Thanks. I am expecting that, if you're looking for a JSONP example, you already know why you need it.

So, here is JSONP example that actually uses the data-set that we mention in the example. Genius. So, to save you the 8-10 hours of rummaging around the internet and trying loads of different things, here is my example.


1. The serving up of the JSON


You need a location on a different server where you have a file that is serving up JSON.

Let's say: http://www.mileage-calculators.co.uk/rest.php

The JSON that this page served up for my testing was simply:

distances (
{
"distanceValues":
[
{
"kilometers":"519.818112",
"miles":"323",
"nauticalmiles":"280.679248"
},
{
"kilometers":"1260.116352",
"miles":"783",
"nauticalmiles":"680.408208"
}
]
}
);
My rest.php file is in PHP so I made sure I had:

<?PHP
header("Content-type: application/json");
?>

at the beginning of the rest.php file.


2. You pull in that JSON using JSONP and jQuery

<script>
$(document).ready(function(){
var urlToUse = 'http://www.mileage-calculators.co.uk/rest.php?callback=?';
$.ajax({
url: urlToUse,
type: 'GET',
async: false,
contentType: "application/json",
data: { q: "test", format: "json" },
dataType: 'jsonp',
jsonpCallback: 'distances',
success: function(json)
{
// console.dir(json);
var text = '';
var len = json.distanceValues.length; // console.dir("JSON Length=" + len);

for(var i=0; i < len; i++)
{
var miles = json.distanceValues[i].miles;
var kilometers = json.distanceValues[i].kilometers;
var nauticalmiles = json.distanceValues[i].nauticalmiles;
text += '<p><strong>Kilometers:</strong> ' + kilometers +'km<br/><strong>Miles:</strong> ' + miles + 'm<br/><strong>Nautical Miles:</strong> ' + nauticalmiles + 'nm<br/></p>'
}
document.getElementById('DataInfo').innerHTML  = text;
},
error: function(e) { console.log(e.message); }
});
});
</script>


In my example, I know the structure of the JSON... so, I roll through the "distanceValues" in a quick loop... create the HTML I want to make for the purpose of my app (which, in this case is just an example) and then I just pop that HTML into a DIV.

Easy Peazy...












Comments