Skip to content

Instantly share code, notes, and snippets.

@bastman
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bastman/8954893 to your computer and use it in GitHub Desktop.
Save bastman/8954893 to your computer and use it in GitHub Desktop.
CrowdparkRpc = {
invokeRpc: function (httpMethod, url, method, params, baseParams, callback) {
var method = '' + method;
if (!params) {
var params = [];
}
var rpc = {
method: method,
params: params
};
if (!baseParams) {
var baseParams = {};
}
for (var key in baseParams) {
rpc[key] = baseParams[key];
}
var requestText;
var exception;
try {
requestText = JSON.stringify(rpc);
} catch (e) {
exception = e;
}
if (exception) {
if (typeof(callback) == 'function') {
callback({
result: null,
error: {
message: 'XHR REQUEST ERROR: ' + exception.message,
requestText: requestText
}
});
}
return;
}
$.ajax({
url: url,
processData: false,
data: requestText,
dataType:'text',
type: httpMethod,
contentType: "application/json",
success: function (responseText) {
var responseData;
var exception;
try {
if (typeof(responseText) == 'string') {
responseData = JSON.parse(responseText);
}
if (typeof(responseData) != 'object') {
throw new Error("XHR ERROR: Invalid rpc response");
}
}
catch (e) {
exception = e;
}
if (typeof(callback) == 'function') {
if (exception) {
callback({
result: null,
error: {
message: 'XHR RESPONSE ERROR: ' + exception.message,
responseText: responseText,
responseData: responseData
}
});
} else {
callback(responseData);
}
}
},
error: function () {
if (typeof(callback) == 'function') {
callback({
result: null,
error: {
message: 'XHR ERROR'
}
});
}
}
});
}
};
CrowdparkRpc.invokeRpc(
'POST',
'ypu-api-url',
"FooService.barMethod",
[
{foo: "bar"}
],
null,
function (response) {
console.log("response=", response);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment