Explorar o código

Merge pull request #42 from xqin/master

Refactor api.js
Wenjie Fan %!s(int64=8) %!d(string=hai) anos
pai
achega
80c6873048
Modificáronse 3 ficheiros con 40 adicións e 34 borrados
  1. 0 0
      dist/DPlayer.min.js
  2. 0 0
      dist/DPlayer.min.js.map
  3. 40 34
      src/api.js

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 0 - 0
dist/DPlayer.min.js


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 0 - 0
dist/DPlayer.min.js.map


+ 40 - 34
src/api.js

@@ -1,43 +1,49 @@
-export const send = (endpoint, danmakuData) => {
-  const xhr = new XMLHttpRequest();
+/*
+ * xhr.status ---> fail
+ * response.code === 1 ---> success
+ * response.code !== 1 ---> error
+ * */
+
+const SendXMLHttpRequest = (url, data, success, error, fail) => {
+  const xhr = new XMLHttpRequest()
+
   xhr.onreadystatechange = () => {
     if (xhr.readyState === 4) {
       if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
-        const response = JSON.parse(xhr.responseText);
+        const response = JSON.parse(xhr.responseText)
+
         if (response.code !== 1) {
-          alert(response.msg);
-        }
-        else {
-          console.log('Post danmaku: ', JSON.parse(xhr.responseText));
+          return error(xhr, response)
         }
+
+        return success(xhr, response)
       }
-      else {
-        console.log('Request was unsuccessful: ' + xhr.status);
-      }
+
+      fail(xhr)
     }
-  };
-  xhr.open('post', endpoint, true);
-  xhr.send(JSON.stringify(danmakuData));
-};
+  }
+
+  xhr.open((data !== null) ? 'POST' : 'GET', url, true)
+  xhr.send((data !== null) ? JSON.stringify(data) : null)
+}
+
+export const send = (endpoint, danmakuData) => {
+  SendXMLHttpRequest(endpoint, danmakuData, (xhr, response) => {
+    console.log('Post danmaku: ', response)
+  }, (xhr, response) => {
+    alert(response.msg)
+  }, (xhr) => {
+    console.log('Request was unsuccessful: ' + xhr.status)
+  })
+}
 
 export const read = (endpoint, cbk) => {
-  const xhr = new XMLHttpRequest();
-  xhr.onreadystatechange = () => {
-    if (xhr.readyState === 4) {
-      if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
-        const response = JSON.parse(xhr.responseText);
-        if (response.code !== 1) {
-          return cbk({ status: xhr.status, response });
-        }
-        else {
-          return cbk(null, response.danmaku);
-        }
-      }
-      else {
-        return cbk({ status: xhr.status, response: null });
-      }
-    }
-  };
-  xhr.open('get', endpoint, true);
-  xhr.send(null);
-};
+  SendXMLHttpRequest(endpoint, null, (xhr, response) => {
+    cbk(null, response.danmaku)
+  }, (xhr, response) => {
+    cbk({ status: xhr.status, response })
+  }, (xhr) => {
+    cbk({ status: xhr.status, response: null })
+  })
+}
+

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio