Look Ma, Cross-Domain Scripting!

Ajax, as I’ve stated time and time again, is sweet. So what is problem? XMLHTTPRequest requires that the called scripts that execute server side and return information to the client must reside on the same domain. This has irked me time and time again during my exploration and experimentation of the Web 2.0 world.

Enter JSON Web Services and dynamic script tags. This beauty allows for Ajax-like communication across domains without requiring page loads. Right right right…so how do you use it? Read on…

First, lets clarify what JSON (JavaScript Object Notation) is. Wikipedia explains that JSON is just a way to structure object data in a way that is easily interpreted…primarily with JavaScript. Here’s some examples from Wikipedia:

JSON Example:

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

Which is the same as this XML Example:

<menu id="file" value="File">
  <popup>
    <menuitem value="New" onclick="CreateNewDoc()" />
    <menuitem value="Open" onclick="OpenDoc()" />
    <menuitem value="Close" onclick="CloseDoc()" />
  </popup>
</menu>

So…if JSON just the data representation part of things, how does it work similarly to Ajax?

Now we’re getting into the Web Services side of things. The quick answer: When you dynamically create <script> tags on a page, the JavaScript source is executed immediately. Now, as most experimental web developers may well know, you can reference remote JavaScript source in a <script> tag. Which means….if you dynamically create a script tag that references a source on another domain, and that source outputs JSON, you are as good as gold!

Here’s the step by step: (I use a JavaScript Object I found over at Dan Theurer’s Blog for the dynamic adding of script elements…it helps avoid duplicate script tags).

First, lets make the remote file that outputs JSON. (obviously, most cases will have the data dynamically generated…but I’ll use a static example as the generation of this data is trivial)

file: remote_file.php

< ?php
echo 'bork({"Image": { "Width":500, "Height":250, "Title":"Giant Cow", "Thumbnail":{"Url":"http://someurl.com/image/1234", "Height": 75, "Width": 150}}});';
?>

Here’s the html file we want the user to see/interact with:

file: client.html

<html>
<head><title>Test</title></head>
<script src="js/jsr_class.js" type="text/javascript"></script>
<script type="text/javascript">
function addScript()
{
  var obj=new JSONscriptRequest('http://someurl.com/remote_file.php');      
  obj.buildScriptTag(); // Build the script tag      
  obj.addScriptTag(); // Execute (add) the script tag
}//end addScript

function bork(data)
{
  var text='';

  if(data==null)
    alert('error');
  else
  {
    text='Image Title: ' + data.Image.Title + '<br />';
    text+='Width: ' + data.Image.Width + '<br />';
    text+='Height: ' + data.Image.Height + '<br />';
    text+='Thumbnail Data: ' + data.Image.Thumbnail.Url;
    text+=' (' + data.Image.Thumbnail.Width + 'x' + data.Image.Thumbnail.Height + ')<br />';
  }
  document.getElementById('output').innerHTML=text;
}//end bork
</script>
<body>
<a href="#" onClick="addScript(); return false;">Click to Get Stuff</a>
<div id="output"></div>
</body>
</html>

Thats all there is to it! Simple and slick.

Posted in Uncategorized