WebRequest.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { sys, _decorator } from 'cc';
  2. export class WebRequest {
  3. private _callBack: Function = null;
  4. private contentType=""
  5. public setContentType(str="application/x-www-form-urlencoded"){
  6. this.contentType=str
  7. }
  8. public getData(url: string, data: any, callback: Function, post: boolean) {
  9. this._callBack = callback;
  10. var self = this;
  11. var xhr = new XMLHttpRequest() //loader.getXMLHttpRequest();
  12. // Simple events
  13. let arr=['loadstart', 'abort', 'error', 'load', 'loadend', 'timeout']
  14. arr.forEach(function (eventname) {
  15. xhr["on" + eventname] = function () {
  16. //log("WebRequest.getData event = " + eventname);
  17. if (eventname == 'abort' || eventname == 'error' || eventname == 'timeout') {
  18. if (self._callBack != null) {
  19. self._callBack(false, "");
  20. }
  21. }
  22. };
  23. });
  24. // Special event
  25. xhr.onreadystatechange = function () {
  26. //log("onreadystatechange code = " + xhr.readyState + ",status = " + xhr.status);
  27. if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
  28. if (self._callBack != null) {
  29. // var XmlToJson = require('XmlToJson');
  30. // var xmlToJson = new XmlToJson();
  31. // var jsonData = JSON.stringify(xmlToJson.parse(xhr.responseText));
  32. self._callBack(true, xhr.response);
  33. }
  34. }
  35. };
  36. xhr.timeout = 5000;//5 seconds for timeout
  37. if (post == null || post == false) {
  38. if (data == "" || data == null) {
  39. xhr.open("GET", url, true);
  40. }
  41. else {
  42. xhr.open("GET", url + "?" + data, true);
  43. }
  44. if (sys.isNative) {
  45. xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
  46. }
  47. xhr.send();
  48. }
  49. else {
  50. //log("open url = " + url + ",data = "+ data);
  51. xhr.open("POST", url, true);
  52. //set Content-type "text/plain" to post ArrayBuffer or ArrayBufferView
  53. // xhr.setRequestHeader("Content-Type","text/plain");
  54. if(this.contentType){
  55. xhr.setRequestHeader("Content-Type", this.contentType);
  56. }
  57. // Uint8Array is an ArrayBufferView
  58. //xhr.send(new Uint8Array([1,2,3,4,5]));
  59. xhr.send(data);
  60. }
  61. }
  62. }