JSONP vs. CORS


A comparison of the new technology (CORS)  vs.
the old hack (JSONP) for getting data cross domain

Karl Gustav Røksund
Accenture
#acntech

Why JSONP




Web server --> Browser --> Other web server

Like JSON but with a "P"





"JSON with padding"





http://en.wikipedia.org/wiki/JSONP‎

How/WHY JSONp Works


The javascript part:
<script>function afunction(json){    var myObj = JSON.parse(json)    console.log(myObj.theJson) //"content" is printed to the console}</script>
The loading...
 <script src="http://otherWebServer.com/some-content.jsonp"></script>
The 'some-content.jsonp' file:
 aFunction('{"theJson": "content"}')

prettifying of the hack



$.ajax({
    url: "http://otherWebServer.com/some-content.jsonp",
    jsonp: "aFunction",
    dataType: "jsonp",
    success: function( json ) {
        var myObj = JSON.parse( json )
        console.log(myObj.theJson) //"content" is printed to the console
    }
});

Best practices



$.ajax({
    url: "http://otherWebServer.com/getSomeJson?callback=?",
    dataType: "jsonp",
    success: function( json ) {
        var myObj = JSON.parse( json )
        console.log(myObj.theJson) //"content" is printed to the console
    }
});




Why cors when JSONp is perfect?





    All that is broken:

    • It ONLY supports get
    • You can only get JSON  (duh)
    • NO headers! And this in turn means:
      • Can't set the 'Accept' type
      • Can't do POST/PUT/DELETE
        (You can do POST in with other hacks) 
      • Authentication headers

    CORS



    "Cross-Origin Resource Sharing"



    Is not a hack but a W3C standard

    Cors example


    Server
    Access-Control-Allow-Origin: *
    Access-Control-Allow-Origin: http://example.com:8080

    Client:
    <!-- Get stuff from the other server just as easily as your own -->




    GREAT why haven't I been using this forevER?



    Short answer: IE

    Long answer: caniuse.com/cors

    Even longer answer:
    ( Even longer answer summed up: We screwed the pooch, please use IE10 )

    EXAMPLE TIME!!!!!!!



    <html><body><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <button onclick="$.get('http://updates.html5rocks.com', function(text){alert(text)})">
    DON'T PUSH THIS BUTTON</button>
    </body></html>

    JSONP vs. CORS

    By pylinux

    JSONP vs. CORS

    • 1,280