Merge pull request #42 from xqin/master

Refactor api.js
This commit is contained in:
Wenjie Fan 2016-12-21 15:37:38 +08:00 committed by GitHub
commit 80c6873048
3 changed files with 44 additions and 38 deletions

6
dist/DPlayer.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -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 })
})
}