A look at jsonserver

I have just taken a brief look at jsonserver. I managed to get it installed without too much trouble except for missing the jsolait installer script. Jsolait is the javascript library that comes with jsonserver to perform the requests. I also installed the kwdemo app to test it out. Now I’m trying to figure out what the role of jsolait will be in the overall implementation of the ajax form framework. Should I go ahead and use jsolait since it already comes with jsonserver? Or should I try to replace the functionality it provides with jQuery?

I went ahead and reimplemented the javascript functions in kwdemo using jQuery. One problem I came across is that jsonserver is setup to accept a json format string in the post (i.e. ‘{“param1″:”Some data”}’), while jQuery is set up to send regular http query strings (i.e. “?param1=Some Data”). Although jQuery can parse a json string into a javascript object, I haven’t found the method (if there is one) to do the reverse.

Just for comparison, here is the code using jsolait:

function test1() {
// injecting plaintext as html
var result = aServer.my_output(test1callback);
}

function test1callback(resp,err){
var node = document.getElementById("appendChild");
if (!err){
node.innerHTML = resp;
}
else
{node.innerHTML = 'Something went wrong!'
}
}

And here is the jQuery version:

function jquerytest1() {
var result = null;
$.ajax({url: '.',
type: 'post',
dataType: 'json',
data: '{"id":1,"method":"my_output", "params":[]}',
contentType: 'application/json-rpc',
success: function(json) {$("#appendChild").append(json.result)},
error: function() {$("#appendChild").append("Something went wrong!")}});
}

Although the jQuery version seems a bit more obfuscated, a lot of it can be simplified by setting presets for the $.ajax() method. But nevertheless you can see how that data string is quite ugly. On the other hand, the response handling is a lot nicer without the if (!err) part. I guess I would like to use the jsolait methods but use jquery response handling syntax, rather than having a straight callback.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 76 other followers

%d bloggers like this: