Lungo.Service.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * External Data & Services Manager
  3. *
  4. * @namespace LUNGO
  5. * @class Service
  6. * @requires Zepto
  7. *
  8. * @author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi
  9. * @author Guillermo Pascual <pasku@tapquo.com> || @pasku1
  10. */
  11. LUNGO.Service = (function(lng, $, undefined) {
  12. /**
  13. * Load data from the server using a HTTP GET request.
  14. *
  15. * @method get
  16. *
  17. * @param {string} Containing the URL to which the request is sent
  18. * @param {object} A map or string that is sent to the server with the request
  19. * @param {Function} [OPTIONAL] Callback function after the request
  20. */
  21. var get = function(url, data, callback) {
  22. var parameters = '?';
  23. for (var parameter in data) {
  24. if (lng.Core.isOwnProperty(data, parameter)) {
  25. if (parameters !== '?') parameters += '&';
  26. parameters += parameter + '=' + data[parameter];
  27. }
  28. }
  29. url = url + parameters;
  30. _ajax('GET', url, null, callback);
  31. };
  32. /**
  33. * Load data from the server using a HTTP POST request.
  34. *
  35. * @method post
  36. *
  37. * @param {string} Containing the URL to which the request is sent
  38. * @param {object} A map or string that is sent to the server with the request
  39. * @param {Function} [OPTIONAL] Callback function after the request
  40. */
  41. var post = function(url, data, callback) {
  42. _ajax('POST', url, data, callback);
  43. };
  44. var _ajax = function(type, url, data, callback, error) {
  45. $.ajax({
  46. type: type,
  47. url: url,
  48. data: data,
  49. dataType: 'json',
  50. success: function(response) {
  51. if (lng.Core.toType(callback) === 'function') {
  52. setTimeout(callback, 100, response);
  53. }
  54. },
  55. error: function(xhr, type) {
  56. if (error) {
  57. setTimeout(error, 100, result);
  58. }
  59. }
  60. });
  61. };
  62. return {
  63. get: get,
  64. post: post
  65. };
  66. })(LUNGO, Zepto);