JsonService.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. define([
  2. "../_base/declare", "../_base/Deferred", "../_base/json", "../_base/lang", "../_base/xhr",
  3. "./RpcService"
  4. ], function(declare, Deferred, json, lang, xhr, RpcService){
  5. // module:
  6. // dojo/rpc/JsonService
  7. return declare("dojo.rpc.JsonService", RpcService, {
  8. // summary:
  9. // TODOC
  10. bustCache: false,
  11. contentType: "application/json-rpc",
  12. lastSubmissionId: 0,
  13. callRemote: function(method, params){
  14. // summary:
  15. // call an arbitrary remote method without requiring it to be
  16. // predefined with SMD
  17. // method: string
  18. // the name of the remote method you want to call.
  19. // params: array
  20. // array of parameters to pass to method
  21. var deferred = new Deferred();
  22. this.bind(method, params, deferred);
  23. return deferred;
  24. },
  25. bind: function(method, parameters, deferredRequestHandler, url){
  26. // summary:
  27. // JSON-RPC bind method. Takes remote method, parameters,
  28. // deferred, and a url, calls createRequest to make a JSON-RPC
  29. // envelope and passes that off with bind.
  30. // method: string
  31. // The name of the method we are calling
  32. // parameters: array
  33. // The parameters we are passing off to the method
  34. // deferredRequestHandler: deferred
  35. // The Deferred object for this particular request
  36. var def = xhr.post({
  37. url: url||this.serviceUrl,
  38. postData: this.createRequest(method, parameters),
  39. contentType: this.contentType,
  40. timeout: this.timeout,
  41. handleAs: "json-comment-optional"
  42. });
  43. def.addCallbacks(this.resultCallback(deferredRequestHandler), this.errorCallback(deferredRequestHandler));
  44. },
  45. createRequest: function(method, params){
  46. // summary:
  47. // create a JSON-RPC envelope for the request
  48. // method: string
  49. // The name of the method we are creating the request for
  50. // params: array
  51. // The array of parameters for this request
  52. var req = { "params": params, "method": method, "id": ++this.lastSubmissionId };
  53. return json.toJson(req);
  54. },
  55. parseResults: function(/*anything*/obj){
  56. // summary:
  57. // parse the result envelope and pass the results back to
  58. // the callback function
  59. // obj: Object
  60. // Object containing envelope of data we receive from the server
  61. if(lang.isObject(obj)){
  62. if("result" in obj){
  63. return obj.result;
  64. }
  65. if("Result" in obj){
  66. return obj.Result;
  67. }
  68. if("ResultSet" in obj){
  69. return obj.ResultSet;
  70. }
  71. }
  72. return obj;
  73. }
  74. });
  75. });