83 lines
3.0 KiB
JavaScript
83 lines
3.0 KiB
JavaScript
$(function () {
|
|
Cookie(function () {
|
|
$('.header-button-left').html(`<a href="./edit.html?s=new">写文章</a>`);
|
|
$('.header-button-right').html(`<a id="logout" href="javascript:;">退出登录</a>`);
|
|
$('#logout').click(function () {
|
|
document.cookie = 'token=;max-age=0'
|
|
window.location.href = '/'
|
|
})
|
|
})
|
|
/**
|
|
* URL /posts
|
|
* 方法 GET
|
|
* 参数 page limit
|
|
* 响应
|
|
* {
|
|
* "page": 1,
|
|
* "limit": 10,
|
|
* "data": [
|
|
* {
|
|
* "ID": 1,
|
|
* "CreatedAt": "2024-08-20T12:00:00Z",
|
|
* "UpdatedAt": "2024-08-20T12:00:00Z",
|
|
* "DeletedAt": null,
|
|
* "Title": "First Post",
|
|
* "Content": "Markdown content here..."
|
|
* }
|
|
* ]
|
|
* }
|
|
**/
|
|
$.ajax({
|
|
url: `${baseUrl}/posts`,
|
|
type: 'GET',
|
|
contentType: 'application/json',
|
|
success: function (data) {
|
|
if (Cookie()) {
|
|
data.data.forEach((item) => {
|
|
$('.post-list').append(`<div class="post-item"><div class="post-title">${item.title}</div><div class="post-message"><div>创建时间:${item.CreatedAt}</div><div>更新时间:${item.UpdatedAt}</div><div><a href="javascript:;" class="post_edit" data-post_id="${item.ID}">编辑</a> <a href="javascript:;" class="post_delete" data-post_id="${item.ID}">删除</a></div></div><div class="post-content">${md.render(item.content)}</div></div>`);
|
|
})
|
|
$('.post_edit').click(function () {
|
|
// 获取post_id
|
|
let post_id = $(this).data('post_id')
|
|
window.location.href = '/edit.html?s=old&id=' + post_id
|
|
})
|
|
$('.post_delete').click(function () {
|
|
// 获取post_id
|
|
let post_id = $(this).data('post_id')
|
|
// 询问是否删除
|
|
if (confirm('确定删除吗?')) {
|
|
$.ajax({
|
|
url: `${baseUrl}/posts/${post_id}`,
|
|
type: 'DELETE',
|
|
contentType: 'application/json',
|
|
beforeSend: function (xhr) {
|
|
xhr.setRequestHeader('Authorization', 'Bearer ' + document.cookie.split('token=')[1].split(';')[0])
|
|
},
|
|
success: function (data) {
|
|
alert('删除成功')
|
|
window.location.reload()
|
|
},
|
|
error: function (xhr, status, error) {
|
|
if (xhr.status === 401) {
|
|
alert('请先登录')
|
|
window.location.href = '/login.html'
|
|
} else {
|
|
alert('删除失败')
|
|
}
|
|
}
|
|
})
|
|
}
|
|
})
|
|
return
|
|
}
|
|
data.data.forEach((item) => {
|
|
$('.post-list').append(`<div class="post-item"><div class="post-title">${item.title}</div><div class="post-message"><div>创建时间:${item.CreatedAt}</div><div>更新时间:${item.UpdatedAt}</div></div><div class="post-content">${md.render(item.content)}</div></div>`);
|
|
})
|
|
},
|
|
error: function (xhr, status, error) {
|
|
|
|
}
|
|
})
|
|
|
|
})
|