/library/HTTPRequest.py

http://pyjamas.googlecode.com/ · Python · 88 lines · 80 code · 6 blank · 2 comment · 2 complexity · 3d0270d098140a45b88605ce57c20e83 MD5 · raw file

  1. from __pyjamas__ import JS
  2. class HTTPRequest:
  3. # also callable as: asyncPost(self, url, postData, handler)
  4. def asyncPost(self, user, pwd, url, postData=None, handler=None):
  5. if postData == None:
  6. return self.asyncPostImpl(None, None, user, pwd, url)
  7. return self.asyncPostImpl(user, pwd, url, postData, handler)
  8. # also callable as: asyncGet(self, url, handler)
  9. def asyncGet(self, user, pwd, url, handler):
  10. if url == None:
  11. return self.asyncGetImpl(None, None, user, pwd)
  12. return self.asyncGetImpl(user, pwd, url, handler)
  13. def createXmlHTTPRequest(self):
  14. return self.doCreateXmlHTTPRequest()
  15. def doCreateXmlHTTPRequest(self):
  16. JS("""
  17. return new XMLHttpRequest();
  18. """)
  19. def asyncPostImpl(self, user, pwd, url, postData, handler):
  20. JS("""
  21. var xmlHttp = this.doCreateXmlHTTPRequest();
  22. try {
  23. xmlHttp.open("POST", url, true);
  24. xmlHttp.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
  25. xmlHttp.onreadystatechange = function() {
  26. if (xmlHttp.readyState == 4) {
  27. delete xmlHttp.onreadystatechange;
  28. var localHandler = handler;
  29. var responseText = xmlHttp.responseText;
  30. var status = xmlHttp.status;
  31. handler = null;
  32. xmlHttp = null;
  33. if(status == 200) {
  34. localHandler.onCompletion(responseText);
  35. } else {
  36. localHandler.onError(responseText, status);
  37. }
  38. }
  39. };
  40. xmlHttp.send(postData);
  41. return true;
  42. }
  43. catch (e) {
  44. delete xmlHttp.onreadystatechange;
  45. handler = null;
  46. xmlHttp = null;
  47. localHandler.onError(String(e));
  48. return false;
  49. }
  50. """)
  51. def asyncGetImpl(self, user, pwd, url, handler):
  52. JS("""
  53. var xmlHttp = this.doCreateXmlHTTPRequest();
  54. try {
  55. xmlHttp.open("GET", url, true);
  56. xmlHttp.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
  57. xmlHttp.onreadystatechange = function() {
  58. if (xmlHttp.readyState == 4) {
  59. delete xmlHttp.onreadystatechange;
  60. var localHandler = handler;
  61. var responseText = xmlHttp.responseText;
  62. var status = xmlHttp.status;
  63. handler = null;
  64. xmlHttp = null;
  65. if(status == 200) {
  66. localHandler.onCompletion(responseText);
  67. } else {
  68. localHandler.onError(responseText, status);
  69. }
  70. }
  71. };
  72. xmlHttp.send('');
  73. return true;
  74. }
  75. catch (e) {
  76. delete xmlHttp.onreadystatechange;
  77. handler = null;
  78. xmlHttp = null;
  79. localHandler.onError(String(e));
  80. return false;
  81. }
  82. """)