Thursday, December 13, 2012

You should use JSON.stringify() and json2.js

Do you find often writing code like the following:

$.ajax({
   url:'/xxx/yyy',
   data: '{action:' + action + ', id:' + id + '}',
   success: function (data) {
      console.log('ajax success...');
   },
   error: function (request, status, error) {
      console.log('ajax error...');
   }
});

Don’t do like that anymore, this code is ugly and buggy! You know that you should use JSON.stringify() for serializing ajax data parameters, don’t you? Buggy code should be changed to the following version:

var args = { 'action': action, 'id': id };
$.ajax({
   url:'/xxx/yyy',
   data: JSON.stringify(args),
   success: function (data) {
      console.log('ajax success...');
   },
   error: function (request, status, error) {
      console.log('ajax error...');
   }
});

Many modern browsers have native implementation for JSON.stringify(). For old ones you should use json2.js. The script automatically makes sure it only adds a JSON.stringify() method if it doesn't already exist so there is no danger including it in a browser that already has native support.