Cross Domain Scripting with AJAX, Again

Thursday, July 17, 2008

I've wrote about how to overcome the cross-domain issue using Apache mod_rewrite. But that'll only work if you have administrator priviledge on your hosting server, most of us don't. So instead of tweaking the server we must tweak the code. Thus, JSON shows up.

JSON(JavaScript Object Notation) is just a way to structure object data.. in a way that is easily interpreted, primarily with Javascript. Some examples from wikipedia:
Javascript

bork({"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}});

and with different format:
XML :
<menu id="file" value="File">
  <popup>
    <menuitem value="New" onclick="CreateNewDoc()" />
    <menuitem value="Open" onclick="OpenDoc()" />
    <menuitem value="Close" onclick="CloseDoc()" />
  </popup>
</menu> 

Aha, so just like xML, JSON is just data representation part of things, but if XML can't handle cross-domain scripting, how can JSON ?

It's because the J letter on JSON, JSON is JavaScript. And we all(well, maybe not all) know that you can reference REMOTE Javascript source inside the <script> tag. So theoritically, if you create a dynamic script tag that references to a script on another domain, that script is executed imediately!. And if the remote script contains JSON, your cross-domain scripting problems days are over!. Yay.

For an even easier way, you can use a js file at Dan Theurer's blog for the dynamic adding of scripts elements.

And here's how you use it.

First, a server side file that creates the JSON outputs, named bork.php
<?php
 echo 'bork({"Image": { "Width":500, "Height":250, "Title":"Giant Cow", 
         "Thumbnail":{"Url":"http://someurl.com/image/1234", 
         "Height": 75, "Width": 150}}});';
?>


And the html file ,bork.html
<html>
<head>
<title>JSON test</title>
<script src="jsr_class.js" type="text/javascript"></script>
<script>
function appendScript(){
 var json=new JSONscriptRequest('http://myotherdomain.com/bork.php?');
 json.buildScriptTag();
 json.addscriptTag();
}

function bork(data){
 var txt='';
 if(data==null)
  alert('error occured');
 else{
  txt='Image Title: '+data.Image.Title+'
'; txt+='Width: '+data.Image.Width+'
'; txt+='Height: '+data.Image.Height+'
'; txt+='Thumbnail Data: '+data.Image.Thumbnail.Url; txt+='('+data.Image.Thumbnail.Width+' x '+data.Image.Thumbnail.Height +')
'; } document.getElementById('bork').innerHTML=txt; } </script> </head> <body> <div id="bork"></div> <a href="#" onClick="appendScript();return false;">Get Bork</a> </body> </html>

Hope this helps.

0 comments: