Thursday, June 17, 2010

JSOND

In my last post, I introduced the Rdb.js library, which allows making requests of an Rdbhost database, provided that the Rdbhost server has been aliased to a subdomain of your domain.

The cross-site data retrieval relies on the data page containing a little executable javascript, that, when loaded into an iframe, changes the iframe 's document.domain to a right-hand subset of the domain that then matches the main frame, similarly treated.

The Rdb.js library handles all this for you, but I describe the method here in case anybody wants to create an alternate library, or modify the library.

The request goes to the server using the client's domain, and with the 'format' parameter set to 'jsond'. The data returned by the server will be formatted similar to:

<html>
<head>
  <script type="text/javascript" >
    window.document.domain=
    "window.document.domain.split('.').slice(-2).join('.');"
  </script></head>
<body>
  <script type="text/plain">
    { ...json here... }
  </script>
</body>
</html>

Lines 4 and 5 execute when the data is loaded into the iframe, changing the domain. It removes all but the rightmost two dot-delimited segments. For example, 'rdbhost.example.com' becomes 'example.com'.

The calling frame also executes the document.domain manipulation so the two have the same domain value. The caller can then load the data from the body script container, and convert it using a JSON parser.

The container is a script with type 'text/plain', as the browsers will leave the contents of such a container uninterpreted, a raw string. The body of the script tag is escaped by replacing all instances of '</' with '<\/'. The JSON parser, or Javascript's eval, will interpret the two identically, so no unescaping is required.

No comments:

Post a Comment