| 83 | } |
| 84 | |
| 85 | export function callHttp(url, object, method, asyncHandler, onError) { |
| 86 | method = method || 'GET'; |
| 87 | |
| 88 | var xhttp = new XMLHttpRequest(); |
| 89 | |
| 90 | var async = !isNull(asyncHandler); |
| 91 | if (async) { |
| 92 | xhttp.onreadystatechange = function () { |
| 93 | if (xhttp.readyState === XMLHttpRequest.DONE) { |
| 94 | if (xhttp.status === 200) { |
| 95 | asyncHandler(xhttp.responseText); |
| 96 | } else if (onError) { |
| 97 | onError(xhttp.status, xhttp.responseText); |
| 98 | } |
| 99 | } |
| 100 | }; |
| 101 | |
| 102 | if (onError) { |
| 103 | xhttp.addEventListener('error', function (event) { |
| 104 | console.log('Failed to execute request'); |
| 105 | console.log(event); |
| 106 | onError(-1, 'Unknown error occurred'); |
| 107 | }); |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | xhttp.open(method, url, async); |
| 112 | xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); |
| 113 | |
| 114 | try { |
| 115 | if (object instanceof FormData) { |
| 116 | xhttp.send(object); |
| 117 | |
| 118 | } else if (!isNull(object)) { |
| 119 | xhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); |
| 120 | xhttp.send(JSON.stringify(object)); |
| 121 | |
| 122 | } else { |
| 123 | xhttp.send(); |
| 124 | } |
| 125 | } catch (error) { |
| 126 | throw new HttpRequestError(xhttp.status, error.message); |
| 127 | } |
| 128 | |
| 129 | if (!async) { |
| 130 | if (xhttp.status === 200) { |
| 131 | return xhttp.responseText; |
| 132 | |
| 133 | } else { |
| 134 | var message = 'Couldn\'t execute request.'; |
| 135 | if (!isNull(xhttp.responseText) && (xhttp.responseText.length > 0)) { |
| 136 | message = xhttp.responseText; |
| 137 | } |
| 138 | throw new HttpRequestError(xhttp.status, message); |
| 139 | } |
| 140 | } else { |
| 141 | return xhttp; |
| 142 | } |