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

73 lines
1.5 KiB
JavaScript
Raw Normal View History

/**
* Handler for JSON rest requests.
**/
Vn.JsonRequest = new Class
({
initialize: function (methodName)
{
this._methodName = methodName;
}
2016-07-22 20:00:27 +00:00
,sendWithUrl: function (params, callback, method, url)
{
var request = new XMLHttpRequest ();
2016-07-22 20:00:27 +00:00
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));
}
2016-07-22 20:00:27 +00:00
,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;
2016-07-22 20:00:27 +00:00
this.sendWithUrl (params, callback, form.method, form.action);
}
});