Tuesday, 10 July 2012

JSON Padding explained

The following is effectively what will happen when using JSON padding in JavaScript.

 <script type="text/javascript">showPrice({symbol: 'IBM', price: 91.42});</script>

  • {...} is the useful JSON data (JavaScript Object formatted) provided by the remote server.
  •  showPrice is the callback function that will need to be defined in the calling script. The padding is also added by the remote server.
  •  In order to achieve all these, the whole lot highlighted will need to be dynamically inserted to the calling script by for example the following:
  <script type="text/javascript">
  // This is our function to be called with JSON data
  function showPrice(data) {
      alert("Symbol: " + data.symbol + ", Price: " + data.price);
  }
  var url = “http://server2.example.com/RetrievePrice?symbol=IBM&jsonp=showPrice”; // URL of the external script
  // this shows dynamic script insertion
  var script = document.createElement('script');
  script.setAttribute('src', url);
 
  // load the script
  document.getElementsByTagName('head')[0].appendChild(script);
  </script>
   
All this is, loosely, due to that JavaScript is not allowed to access foreign domain code, except from within. i.e. "... the domain of the requested URL must be the same as the domain of the current Web page ..." --- source

No comments: