HttpUtils.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. var httpUtils = cc.Class({
  2. extends: cc.Component,
  3. properties: {
  4. // foo: {
  5. // default: null, // The default value will be used only when the component attaching
  6. // to a node for the first time
  7. // url: cc.Texture2D, // optional, default is typeof default
  8. // serializable: true, // optional, default is true
  9. // visible: true, // optional, default is true
  10. // displayName: 'Foo', // optional
  11. // readonly: false, // optional, default is false
  12. // },
  13. // ...
  14. },
  15. statics: {
  16. instance: null
  17. },
  18. // use this for initialization
  19. onLoad: function() {},
  20. httpGets: function(url, callback) {
  21. var xhr = cc.loader.getXMLHttpRequest();
  22. xhr.onreadystatechange = function() {
  23. if (xhr.readyState == 4) {
  24. if (xhr.status >= 200 && xhr.status < 400) {
  25. var response = xhr.responseText;
  26. if (response) {
  27. // var responseJson = JSON.parse(response);
  28. callback(response);
  29. } else {
  30. console.log("返回数据不存在");
  31. callback(-1);
  32. }
  33. } else {
  34. console.log("请求失败");
  35. callback(-1);
  36. }
  37. }
  38. };
  39. xhr.open("GET", url, true);
  40. xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  41. if (cc.sys.isNative) {
  42. xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
  43. }
  44. // note: In Internet Explorer, the timeout property may be set only after calling the open()
  45. // method and before calling the send() method.
  46. xhr.timeout = 5000; // 5 seconds for timeout
  47. xhr.send();
  48. },
  49. httpPost: function(url, params, callback) {
  50. var xhr = cc.loader.getXMLHttpRequest();
  51. xhr.onreadystatechange = function() {
  52. if (xhr.readyState == 4) {
  53. if (xhr.status >= 200 && xhr.status < 400) {
  54. var response = xhr.responseText;
  55. // console.log(response)
  56. if (response) {
  57. // var responseJson = JSON.parse(response);
  58. callback(response);
  59. } else {
  60. console.log("返回数据不存在");
  61. callback(-1);
  62. }
  63. } else {
  64. console.log("请求失败");
  65. callback(-1);
  66. }
  67. }
  68. };
  69. xhr.open("POST", url, true);
  70. xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  71. if (cc.sys.isNative) {
  72. xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
  73. }
  74. // note: In Internet Explorer, the timeout property may be set only after calling the open()
  75. // method and before calling the send() method.
  76. xhr.timeout = 5000; // 5 seconds for timeout
  77. xhr.send(params);
  78. }
  79. });
  80. httpUtils.getInstance = function() {
  81. if (httpUtils.instance == null) {
  82. httpUtils.instance = new httpUtils();
  83. }
  84. return httpUtils.instance;
  85. };