Most examples these days use jquery to load jsonp data.
If you want to develop a simple javascript widget then it might not be a good option to include jquery in your code.
In this example I’ll show you how to load html from a server in any domain and display it with a javascript.
It’s actually very simple to load jsonp data without using any javascript libraries.
The trick is to load your data in a script tag like so:
<script type="text/javascript" src="http://subclosure.com/demos/getjsonpdata.php"></script>
The server needs to return a json object that is wrapped in a function, e.g.:
callback({"html":"hello jsonp"})
In PHP you can do it easily like this:
echo 'callback(' . json_encode(array('html' => 'hello jsonp')) . ')' ;
Now when this script is loaded into the browser, it will call the function named callback (you can call this function whatever you like).
You just need to provide a handler for this function call and that’s pretty much it:
<div id = 'mycontent'></div>
<script>
function callback(jsondata){
document.getElementById('mycontent').innerHTML = jsondata.html ;
}
</script>
<script type="text/javascript" src="http://subclosure.com/demos/getjsonpdata.php"></script>
Here is a working script example: http://subclosure.com/demos/getjsonp.html
Comments
Leave a comment Trackback