/
index.js
114 lines (101 loc) · 2.98 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
function escape(toOutput) {
return toOutput.replace(/\&/g, '&')
.replace(/\</g, '<')
.replace(/\>/g, '>')
.replace(/\"/g, '"')
.replace(/\'/g, ''')
.replace(/\//g, '/');
}
function appendCommentToDOM(container, comment, isPrepend) {
const html = `
<div class="card">
<div class="card-body">
<div class="d-flex justify-content-between">
<div class="d-flex">
<div class="card_avartar text-center text-white">
${comment.id}
</div>
<h5 class="card-title">${comment.nickname}</h5>
</div>
<p>${comment.created_at}</p>
</div>
<p class="card-text">${comment.content}</p>
</div>
</div>
`
if (isPrepend) {
container.prepend(html)
} else {
container.append(html)
}
}
function getCommentsAPI(siteKey, before, cb) {
let url = `https://tzutzu858.tw/json/api_comments.php?site_key=${siteKey}`
if (before) {
url += '&before=' + before
}
$.ajax({
url,
}).done(function (data) {
cb(data)
});
}
function getComments() {
$('.load-more').hide();
getCommentsAPI(siteKey, lastId, data => {
const commentsDOM = $('.comments')
if (!data.ok) {
alert(data.message)
return
}
const comments = data.discussions;
for (let comment of comments) {
appendCommentToDOM(commentsDOM, comment)
}
let length = comments.length
if (length < 5) {
$('.load-more').hide();
return
} else {
lastId = comments[length - 1].id
commentsDOM.append(loadMoreButtonHTML)
}
})
}
const siteKey = 'tzu'
const loadMoreButtonHTML = '<button class="load-more btn btn-primary">載入更多</button>'
let lastId = null
$(document).ready(() => {
const commentsDOM = $('.comments')
//第一次載入資料
getComments();
// 載入更多
$('.comments').on('click', '.load-more', () => {
getComments();
})
// 新增留言
$('.add-comment-form').submit(e => {
e.preventDefault();
const newCommentData = {
site_key: 'tzu',
nickname: $('input[name=nickname]').val(),
content: $('textarea[name=content]').val()
}
$.ajax({
type: 'POST',
url: 'https://tzutzu858.tw/json/api_add_comments.php',
data: newCommentData
}).done(function (data) {
if (!data.ok) {
alert(data.message)
return
}
$('input[name=nickname]').val('') // 成功之後傳個空字串清空
$('textarea[name=content]').val('')
const comments = data.discussions;
for (let comment of comments) {
appendCommentToDOM(commentsDOM, comment, true)
}
});
})
})