QypeApi.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. qype.API = {
  2. API_KEY: "NvuKeZPbV92DGlTpiqBOYQ",
  3. /**
  4. * Common function to fetch data from the Qype API. Takes care of setting the
  5. * needed HTTP headers etc.
  6. *
  7. * Examples:
  8. * qype.API.get("places", "42")
  9. * qype.API.get("places", "42",
  10. * { "foo": 1 },
  11. * {
  12. * "onSuccess": function() { alert("success!"); },
  13. * "onFailure": function() { alert("failure!"); }
  14. * })
  15. *
  16. * @param {String} target The target Qype API command (e.g. "places")
  17. * @param {String} path Path to be appended to the base url (e.g. "42") (optional)
  18. * @param {Object} params Parameters to be appended to the url (optional)
  19. * @param {Object} callbacks Callbacks, should contain at least
  20. * onSuccess and onFailure callbacks. (optional)
  21. */
  22. get: function(target, callbacks, path, params) {
  23. var url = "http://api.qype.com/v1/" + target + (path ? ("/"+path) : "");
  24. params = params || {};
  25. params.consumer_key = this.API_KEY
  26. callbacks = callbacks || this.defaultCallbacks;
  27. new Ajax.Request(url, {
  28. method: "get",
  29. parameters: params,
  30. requestHeaders: {
  31. "Accept": "application/json",
  32. "Accept-Language": "en_GB"
  33. },
  34. onSuccess: function(response) {
  35. if(!response.status) {
  36. callbacks.onFailure(response);
  37. } else {
  38. callbacks.onSuccess(response);
  39. }
  40. },
  41. onFailure: callbacks.onFailure
  42. });
  43. },
  44. defaultCallbacks: {
  45. onSuccess: function(response) {
  46. util.log("{Qype.API} onSuccess:");
  47. util.log(response);
  48. },
  49. onFailure: function(response) {
  50. util.log("{Qype.API} onFailure:");
  51. util.log(response);
  52. }
  53. }
  54. };