api.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * xhr.status ---> fail
  3. * response.code === 0 ---> success
  4. * response.code !== 0 ---> error
  5. * */
  6. const SendXMLHttpRequest = (url, data, success, error, fail) => {
  7. const xhr = new XMLHttpRequest();
  8. xhr.onreadystatechange = () => {
  9. if (xhr.readyState === 4) {
  10. if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
  11. const response = JSON.parse(xhr.responseText);
  12. if (response.code !== 0) {
  13. return error(xhr, response);
  14. }
  15. return success(xhr, response);
  16. }
  17. fail(xhr);
  18. }
  19. };
  20. xhr.open(data !== null ? 'POST' : 'GET', url, true);
  21. xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
  22. xhr.send(data !== null ? JSON.stringify(data) : null);
  23. };
  24. export default {
  25. send: (endpoint, danmakuData, callback) => {
  26. SendXMLHttpRequest(endpoint, danmakuData, (xhr, response) => {
  27. console.log('Post danmaku: ', response);
  28. if (callback) {
  29. callback();
  30. }
  31. }, (xhr, response) => {
  32. alert(response.msg);
  33. }, (xhr) => {
  34. console.log('Request was unsuccessful: ' + xhr.status);
  35. });
  36. },
  37. read: (endpoint, callback) => {
  38. SendXMLHttpRequest(endpoint, null, (xhr, response) => {
  39. callback(null, response.danmaku);
  40. }, (xhr, response) => {
  41. callback({ status: xhr.status, response });
  42. }, (xhr) => {
  43. callback({ status: xhr.status, response: null });
  44. });
  45. }
  46. };