| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- import { sys, _decorator } from 'cc';
- export class WebRequest {
- private _callBack: Function = null;
- private contentType=""
- public setContentType(str="application/x-www-form-urlencoded"){
- this.contentType=str
- }
- public getData(url: string, data: any, callback: Function, post: boolean) {
- this._callBack = callback;
- var self = this;
- var xhr = new XMLHttpRequest() //loader.getXMLHttpRequest();
- // Simple events
- let arr=['loadstart', 'abort', 'error', 'load', 'loadend', 'timeout']
- arr.forEach(function (eventname) {
- xhr["on" + eventname] = function () {
- //log("WebRequest.getData event = " + eventname);
- if (eventname == 'abort' || eventname == 'error' || eventname == 'timeout') {
- if (self._callBack != null) {
- self._callBack(false, "");
- }
- }
- };
- });
- // Special event
- xhr.onreadystatechange = function () {
- //log("onreadystatechange code = " + xhr.readyState + ",status = " + xhr.status);
- if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
- if (self._callBack != null) {
- // var XmlToJson = require('XmlToJson');
- // var xmlToJson = new XmlToJson();
- // var jsonData = JSON.stringify(xmlToJson.parse(xhr.responseText));
- self._callBack(true, xhr.response);
- }
- }
- };
- xhr.timeout = 5000;//5 seconds for timeout
- if (post == null || post == false) {
- if (data == "" || data == null) {
- xhr.open("GET", url, true);
- }
- else {
- xhr.open("GET", url + "?" + data, true);
- }
- if (sys.isNative) {
- xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
- }
- xhr.send();
- }
- else {
- //log("open url = " + url + ",data = "+ data);
- xhr.open("POST", url, true);
- //set Content-type "text/plain" to post ArrayBuffer or ArrayBufferView
- // xhr.setRequestHeader("Content-Type","text/plain");
- if(this.contentType){
- xhr.setRequestHeader("Content-Type", this.contentType);
- }
- // Uint8Array is an ArrayBufferView
- //xhr.send(new Uint8Array([1,2,3,4,5]));
- xhr.send(data);
- }
- }
-
- }
|