89 lines
1.8 KiB
JavaScript
89 lines
1.8 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)
|
|
{
|
|
var url = 'json.php?method='+ encodeURIComponent (this._methodName);
|
|
this.sendWithUrl (params, callback, 'post', url);
|
|
}
|
|
|
|
,_onStateChange: function (request, callback)
|
|
{
|
|
if (request.readyState !== 4)
|
|
return;
|
|
|
|
var data = null;
|
|
var error = null;
|
|
|
|
try {
|
|
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);
|
|
}
|
|
|
|
,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);
|
|
}
|
|
|
|
,sendFormMultipart: function (form, callback)
|
|
{
|
|
var request = new XMLHttpRequest ();
|
|
request.open (form.method, form.action, true);
|
|
request.onreadystatechange =
|
|
this._onStateChange.bind (this, request, callback);
|
|
request.send (new FormData (form));
|
|
}
|
|
});
|
|
|