Using JSON in javascript

Why JSON

With all the world using XML, why JSON ? We are trying to develop applications in browsers. Javascript is not the fastest of languages to execute and we wanted to make the best use of the compute capacity available on a browser. This will enable us to do more of use to the user on the browser rather than spending time decoding a foreign format. For this reason we have standardized on JSON as the communication format since the parse is native to the javascript language and consequently very fast.

To make Widget development easier in Sakai we have started to build the SData service that will over time provide all the JSON based services that a widget developer will need from Sakai. This service already provides Content Storage (both CHS and JCR), Personal Storage (both CHS and JCR), Current User Profile, Recent Changes, several forms of search, announcements, rss aggrigation and a number of other services.

For a widget to provide user interactivity it needs to communicate with these services. To make this easier the SData client side contains a simple class that encapsulates all ajax operations.

Although we are using JSON and the SData service, this is a 100% inclusive development methodology, and you can use whatever techniques you want to serve the html and provide the data feeds, provided the resulting widget interacts correctly with the widget container. We just happen to think that JSON and HTML makes sense.

A simple Example - message of the day

In this example, we are retrieving a block of JSON from the message of the day service. The block comes back as a string, which we encapsulate in ( and ) and then evaluate to generate an object. In this simple case we pass that object directly to a template for rendering and generate an HTML fragment which we append to a div in the widget. If the ajax call fails, the onFail function will be called and the user alerted.

Get Message Of The Day Snippet
var CodeExample1 = {
      demo : function() {
          SData.ajax({
              url : "/sdata/motd",
              onSuccess : function(data) {
                  var context = eval( '(' + data + ')' );
                  // evaluate the tempalte in div helloworld_template1 with context
                  var r = SData.Template.render("helloworld_motd_template1",context);
            
                  // append the result to the div helloworld_message to display the message of the day
                  document.getElementById("helloworld_message").innerHTML += r;				
              },
              onFail : function(status) {
          	alert("Oh dear no message of the day server said "+status);
              }
          });
      }
}

Post a form

In this example we are posting an array of URI's to the collection service, that will resolve the URI's into JSON representations of item listings and return that. To perform the POST we create an array of object with name value properties. In this case we really do want to post an array of parameters called 'uri'. We set the method to POST and we set the contentType to application/x-www-form-urlencoded to format the content correctly for a post.

The SData.ajax method will read the data structure and convert it into the correct format. Once this has been posted to the server, it will invoke the onSucess method if the call was successful and the onFail if the call failed.

Posting a form
var CodeExample2 = {
          show_collection : function(arrayOfResourceUrls){
	  	var list = arrayOfResourceUrls;
	  	var url = "/sdata/col";
	  	var postData = [];
		
	  	for (var i=0; i<arrayOfResourceUrls.length; i++)
	  	{
	      		postData[i] = new Object();
	      		postData[i].name = 'uri';
	      		postData[i].value = arrayOfResourceUrls[i];
	  	}
				
	  	SData.ajax({
			url : url,
			postData : postData,
			httpMethod: "POST",
			contentType: "application/x-www-form-urlencoded",
			onSuccess : function(data) {
				_CView.show_folder(data);
			},
			onFail : function(status) {
				_CView.show(status,false);
			}
	   	});
	   }
}

Upload a file to personal storage.

A slightly more complex example is shown below, uploading a file to the personal storage service. In this example we are not processing JSON, but we are uploading data to the personal storage service. This data is represented as a string (fileContent) and will be saved under a folder mysavespace for the current user in a file specified by fileName.

Prior to the ajax call we create a Javascript object to specify the upload. This an array objects (in this case one object named items) each object with the properties data, fileName and contentType. The Ajax call when it sees a httpMethod of POST and a contentType of multipart/form-data will generate a multipart form data post containing one block per element of the data array. Each block will use the members of that element to specifiy the upload.

As will all calls to SData.ajax, the onSucess function is invoked when the asynchronous call is successful. In this case the user is informed that the save was successful.

Get Message Of The Day Snippet
var DemoSaveFile = {
    
    saveFile  : function(fileName, fileContents){
        if (path && path.length > 0 && fileContents != null) {
           // data can contain many items each item that contains a data, fileName and contentType member will
           // be sent as a file upload in the multipart form-data post
	   var data = {"items": {"data": fileContents, "fileName": fileName, "contentType": "text/plain"}};

	   SData.ajax({
	       url : "sdata/p/mysavespace",
	       httpMethod : "POST",
	       onSuccess : function(data){
		  alert("Save Sucessfull to "+fileName);
               },
   	       postData : data,
	       contentType : "multipart/form-data"
	   });
	}
     }
}
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.