本文章目標:收集文章內容,并提交服務器保存
一:基于form-serialize插件收集表單數據
form-serialize插件僅能收集到表單數據,除此之外的數據無法收集到
二:基于axios提交到服務器保存
三:調用alert警告框反饋結果給用戶
alert警告框部分是調用之前封裝好的js庫,利用到了封裝函數思想
function myAlert(isSuccess, msg) {const alert = document.querySelector('.alert')alert.classList.add(isSuccess ? 'alert-success' : 'alert-danger')alert.innerHTML = msgalert.classList.add('show')setTimeout(() => {alert.classList.remove(isSuccess ? 'alert-success' : 'alert-danger')alert.innerHTML = ''alert.classList.remove('show')}, 1500);
}
四:重置表單并跳轉到列表頁
// 3.1 基于 form-serialize 插件收集表單數據對象
document.querySelector('.send').addEventListener('click', async e => {if (e.target.innerHTML !== '發布') returnconst form = document.querySelector('.art-form')const data = serialize(form, { hash: true, empty: true })// 發布文章的時候,不需要 id 屬性,所以可以刪除掉(id 為了后續做編輯使用)delete data.idconsole.log(data)// 自己收集封面圖片地址并保存到 data 對象中data.cover = {type: 1, // 封面類型images: [document.querySelector('.rounded').src] // 封面圖片 URL 網址}// 3.2 基于 axios 提交到服務器保存try {const res = await axios({url: '/v1_0/mp/articles',method: 'POST',data: data})// 3.3 調用 Alert 警告框反饋結果給用戶myAlert(true, '發布成功')// 3.4 重置表單并跳轉到列表頁form.reset()// 封面需要手動重置document.querySelector('.rounded').src = ''document.querySelector('.rounded').classList.remove('show')document.querySelector('.place').classList.remove('hide')// 富文本編輯器重置editor.setHtml('')setTimeout(() => {location.href = '../content/index.html'}, 1500)} catch (error) {myAlert(false, error.response.data.message)}
})