/** * Handler for JSON rest requests. **/ Vn.JsonRequest = new Class ({ initialize: function (methodName) { this._methodName = methodName; } ,sendWithUrl: function (params, callback, method, url) { var request = new XMLHttpRequest (); request.open (method, url, true); request.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded'); request.onreadystatechange = this._onStateChange.bind (this, request, callback); request.send (Vn.Url.makeUri (params)); } ,send: function (params, callback) { var url = 'rest.php?method='+ encodeURIComponent (this._methodName); this.sendWithUrl (params, callback, 'post', url); } ,_onStateChange: function (request, callback) { if (request.readyState !== 4) return; var jsData = null; var error = null; try { if (request.status !== 200) throw new Error (request.statusText); var json = JSON.parse (request.responseText); var jsData = json.data; var jsError = json.error; if (jsError) throw new Vn.Error ( jsError.domain, jsError.code, jsError.message); } catch (e) { jsData = null; error = e; } if (callback) callback (this, jsData, error); } ,sendForm: function (form, callback) { var params = {}; var elements = form.elements; for (var i = 0; i < elements.length; i++) if (elements[i].name) params[elements[i].name] = elements[i].value; this.sendWithUrl (params, callback, form.method, form.action); } });