hedera-web/js/vn/json-request.js

117 lines
2.3 KiB
JavaScript

/**
* 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)
{
if (!params)
params = {};
params['srv'] = 'json:'+ this._methodName;
this.sendWithUrl (params, callback, 'post', '.');
}
,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, 'post', form.action);
}
,sendFormMultipart: function (form, callback)
{
var request = new XMLHttpRequest ();
request.open ('post', form.action, true);
request.onreadystatechange =
this._onStateChange.bind (this, request, callback);
request.send (new FormData (form));
}
,_onStateChange: function (request, callback)
{
if (request.readyState !== 4)
return;
var data = null;
var error = null;
try {
if (request.status == 0)
{
var ex = new Vn.JsonException ();
ex.message = _('The server does not respond');
throw ex;
}
var contentType = null;
try {
contentType = request
.getResponseHeader ('Content-Type')
.split (';')[0]
.trim ();
}
catch (e) {}
if (contentType != 'application/json')
{
var ex = new Vn.JsonException ();
ex.message = request.statusText;
ex.code = request.status;
throw ex;
}
var json = JSON.parse (request.responseText);
var jsData = json.data;
var jsWarns = json.warnings;
if (request.status == 200)
{
data = jsData;
}
else
{
var ex = new Vn.JsonException ();
ex.exception = jsData.exception;
ex.message = jsData.message;
ex.code = jsData.code;
ex.file = jsData.file;
ex.line = jsData.line;
ex.trace = jsData.trace;
throw ex;
}
}
catch (e)
{
data = null;
error = e;
}
if (callback)
callback (this, data, error);
}
});