970_90

Tuesday, 2 July 2013

Difference between JSON and JSONP

Difference between JSON and JSONP

Full Form of JSON
JavaScript Object Notation

Full Form of JSONP
JavaScript Object Notation with Padding.



Json is stardard format that is human readable used to transmit information from one server to another server.
Jsonp is a json with ability to transmit information to another domain.



JSONP is JSON with padding, that is, you put a string at the beginning and a pair of parenthesis around it. 

JSON Example
{"Name": "Foo", "Id": 1234, "Rank": 7};

JSONP Example - In this you can call a function
functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});




With JSON you can't send request to another domain whereas JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. In JSONP you can send request to a different domain.) 
Demo with JSONP
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=5',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var htmlData = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            htmlData += '<p>
<img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>
'
                        }
                        $('#MyTwitterFeed').html(htmlData);
                    }
                });
            })
        </script>
        <div id="MyTwitterFeed">
</div>



1 comment: