JSON Versus JSONP Tutorial

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

26/7/2016 JSONversusJSONPTutorial

JSONversusJSONPTutorialLive

JSONPisasimplewaytoovercomebrowserrestrictionswhensendingJSONresponses
fromdifferentdomainsfromtheclient.

Butthepracticalimplementationoftheapproachinvolvessubtledifferencesthatareoften
notexplainedclearly.

HereisasimpletutorialthatshowsJSONandJSONPsidebyside.

AllthecodeisfreelyavailableatGithubandaliveversioncanbefoundathttp://json
jsonptutorial.craic.com

JSON(JavascriptObjectNotation)isaconvenientwaytotransportdatabetween
applications,especiallywhenthedestinationisaJavascriptapplication.

JQueryhasfunctionsthatmakeAjax/HTTPDcallsfromascripttoaserververyeasyand
$.getJSON()isagreatshorthandfunctionforfetchingaserverresponseinJSON.

Butthissimpleapproachfailsifthepagemakingtheajaxcallisinadifferentdomainfrom
theserver.TheSameOriginPolicyprohibitsthesecrossdomaincallsinsomebrowsersasa
securitymeasure.

Atthetimeofwriting,GoogleChromeversion24andMozillaFirefoxversion17donot
appeartoapplythisrestrictionbutInternetExplorerversion9does.

Thesecurityimplicationsofallowingcrossdomainrequestsshouldbeconsideredcarefully
inyourapplicationbutifyoudowanttoallowthemthenyouneedawaytoovercomethe
browserrestrictions.

JSONP(JSONwithPadding)makesthispossibleinallbrowsers.

JSONPwrapsupaJSONresponseintoaJavaScriptfunctionandsendsthatbackasa
Scripttothebrowser.AscriptisnotsubjecttotheSameOriginPolicyandwhenloaded
intotheclient,thefunctionactsjustliketheJSONobjectthatitcontains.

ThispageshowsthetwoapproacheswithsnippetsofServerandClientcode.Lookatthe
sourceofthispagetoseethefullJScode.

ThecodeconsistsofaServerapplication,implementedhereasaRubySinatraapplication.
YoushouldbefamiliarwithRuby,GemsandbasicSinatraapps,ifyouwanttorunalive
demo.

Youcanrunitlocallywiththecommands'bundleinstall'and'rackupp4567'andthen
goingto'http://localhost:4567'withyourbrowser.

NOTE:Toreallydemonstratethecrossdomainoperationyouneedtoputtheclientand
servercodeonTWODIFFERENTmachines.Runthispageonyourlocalhostandchangethe
'host'intheJStopointto'http://jsonjsonptutorial.craic.com'.

TheexamplesmakeuseoftheJSON.stringifymethodfromDouglasCrockfordto'pretty
print'thereturnedJSON.YoucanfindthatHERE.

JSON
HereisaminimalexamplethatusesJSONasthetransportfortheserverresponse.The

http://jsonjsonptutorial.craic.com/index.html 1/3
26/7/2016 JSONversusJSONPTutorial

clientmakesanajaxrequestwiththeJQueryshorthandfunction$.getJSON.Theserver
generatesahash,formatsitasJSONandreturnsthistotheclient.Theclientformatsthis
andputsitinapageelement.

Server:

get'/json'do
content_type:json
content={:response=>'SentviaJSON',
:timestamp=>Time.now,
:random=>rand(10000)}
content.to_json
end

Client:

varurl=host_prefix+'/json';
$.getJSON(url,function(json){
$("#jsonresponse").html(JSON.stringify(json,null,2));
});

GetJSONresponse

JSONP
TheonlychangeontheClientsidewithJSONPistoaddacallbackparametertotheURL.
Thesimplestwaytodothisistoadd'callback=?'inwhichcasejQuerywillgeneratea
uniquefunctionnameandpassthattotheserver(e.g.
jQuery19009536794223822653_1359406689359).

OntheServeryouneedtogetthe'callback'parameterand,insteadofreturningtheraw
JSON,youwrapthatstringinafunctiondefinition,likethis"()".Youdon'tneedtoknow
thefunctionnameinadvanceyoujustgetitfromthatcallbackparameter.

Youshouldalsosetthecontenttypeto'application/javascript',althoughthisdoesn't
appeartomatterinmytests.

BackontheclientsideyoutreatthereturnedfunctionjustliketherawJSONobject.

Server:

get'/jsonp'do
callback=params['callback']
content_type:js
content={:response=>'SentviaJSONP',
:timestamp=>Time.now,
:random=>rand(10000)}
"#{callback}(#{content.to_json})"
end

Client:

varurl=host_prefix+'/jsonp?callback=?';
$.getJSON(url,function(jsonp){
$("#jsonpresponse").html(JSON.stringify(jsonp,null,2));
});

GetJSONPresponse

http://jsonjsonptutorial.craic.com/index.html 2/3
26/7/2016 JSONversusJSONPTutorial

AprojectfromCraic Copyright2013RobertJones,CraicComputingLLC(Distributedunder
Computing thetermsoftheMITLicense)

http://jsonjsonptutorial.craic.com/index.html 3/3

You might also like