1 include(bbq.ajax.AJAXRequest);
  2 include(bbq.gui.error.ServerError);
  3 include(bbq.lang.TreeWalker);
  4 
  5 bbq.ajax.JSONRequest = Class.create(bbq.ajax.AJAXRequest, /** @lends bbq.ajax.JSONRequest.prototype */ {
  6 
  7 	/**
  8 	 * Sends an asynchronous HTTP request to a server.  The passed arguments are serialized to a
  9 	 * JSON string and the response is also expected to be a JSON string.  The request goes out
 10 	 * as a POST request and the JSON string is sent as the request body.
 11 	 *
 12 	 * @example
 13 	 *<pre><code class="language-javascript">
 14 	 * new bbq.ajax.JSONRequest({
 15 	 *     // The URL to send the request to - can be relative
 16 	 *     url: "/some/path",
 17 	 *
 18 	 *     // The arguments to send - N.B. will be JSON serialized
 19 	 *     args: {
 20 	 *          foo: "bar"
 21 	 *     }
 22 	 *
 23 	 *     // Invoked on success.
 24 	 *      // The first argument is the XMLHTTPRequest object,
 25 	 *      // the second is the deserialized server response
 26 	 *     onSuccess: function(serverResponse, json) {
 27 	 *
 28 	 *     },
 29 	 *
 30 	 *     // Invoked when the request fails - eg. a X-BBQ-ResponseCode
 31 	 *     // header is sent with a negative value
 32 	 *     onFailure: function() {
 33 	 *
 34 	 *     }
 35 	 * });
 36 	 * </code></pre>
 37 	 *
 38 	 * @constructs
 39 	 * @param {Object} options
 40 	 * @extends bbq.ajax.AJAXRequest
 41 	 */
 42 	initialize: function($super, options) {
 43 		// override content type
 44 		options.contentType = "application/json";
 45 		
 46 		$super(options);
 47 	},
 48 
 49 	/**
 50 	 * @param {String} handlerName
 51 	 * @param {Object} args
 52 	 */
 53 	_callHandler: function($super, handlerName, args) {
 54 		var serverResponse = args[0];
 55 		var json = {};
 56 		var contentType = serverResponse.getHeader("Content-Type");
 57 
 58 		if(contentType && contentType.indexOf("application/json") != -1 && serverResponse.responseText != "") {
 59 			// only attempt decode JSON if the response content type is application/json
 60 			try {
 61 				json = serverResponse.responseText.evalJSON(true);
 62 			} catch(e) {
 63 				Log.error("Error de-escaping JSON", e);
 64 			}
 65 		}
 66 
 67 		$super(handlerName, [serverResponse, json]);
 68 	},
 69 
 70 	_getPostBody: function() {
 71 		return Object.toJSON(this.options.args);
 72 	},
 73 
 74 	_createRequestHeaders: function() {
 75 		return {
 76 			"Accept": "application/json;charset=UTF-8"
 77 		};
 78 	}
 79 });
 80