Wilson@思源

目 录

嵌入SQL查询自定义字段

方法1
效果
js
//!js return (async () => { const sql = ` select * from blocks where type = 'd' limit 2; `; const result = await query(sql); render(result); function render(result) { let html = ''; result.forEach(item => { html += `
${item.content}${item.hpath}${formatDateTime(item.created)}
`; }); setTimeout(() => { item.querySelector('.b3-form__space--small').outerHTML = html; }, 40); } function formatDateTime(str) { const year = str.substring(0, 4); const month = str.substring(4, 6); const day = str.substring(6, 8); const hours = str.substring(8, 10); const minutes = str.substring(10, 12); const seconds = str.substring(12); return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; } // 通过SQL查询数据 async function query(sql) { const result = await fetchSyncPost('/api/query/sql', { "stmt": sql }); if (result.code !== 0) { console.error("查询数据库出错", result.msg); return []; } return result.data; } // 请求api async function fetchSyncPost(url, data) { const init = { method: "POST", }; if (data) { if (data instanceof FormData) { init.body = data; } else { init.body = JSON.stringify(data); } } try { const res = await fetch(url, init); const res2 = await res.json(); return res2; } catch (e) { console.log(e) return []; } } // 固定返回空值 return []; })();
方法2
参考 查询不在数据库中的文档