WP DEVELOP

EP096. “新建笔记表单与 REST API 创建请求”

首页 WordPress 开发课程 MY NOTES 前端功能 · EP096
约 11 分钟· #EP096#MY NOTES 前端功能
🔒 登录后可标记已读

CRUD 的最后一块拼图:Create。在 My Notes 页面顶部加一个新建笔记的表单(标题输入框 + 正文文本域 + 提交按钮),点击提交后用 $.ajax() 发一个不带 ID 的 POST 请求——请求地址不带具体 ID,WordPress REST API 就会把它理解成「新建一条」而不是「更新某一条」。这一讲先用占位文字确认新建流程整体走通,下一讲(part 2)再把占位文字换成用服务器真实返回的数据渲染。


涉及文件

  • wp-content/themes/fictional-university-theme/page-my-notes.php (修改)
  • wp-content/themes/fictional-university-theme/src/modules/MyNotes.js (修改)

代码实现

page-my-notes.php:在笔记列表上方新增建笔记表单

<div class="create-note">
  <h2 class="headline headline--medium">Create New Note</h2>
  <input class="new-note-title" placeholder="Title">
  <textarea class="new-note-body" placeholder="Your note here..."></textarea>
  <span class="submit-note">Create Note</span>
</div>

src/modules/MyNotes.jsevents() 新增监听,createNote() 复制自 updateNote() 改造

// wp-content/themes/fictional-university-theme/src/modules/MyNotes.js

events() {
  $(".delete-note").on("click", this.deleteNote)
  $(".edit-note").on("click", this.editNote.bind(this))
  $(".update-note").on("click", this.updateNote.bind(this))
  $(".submit-note").on("click", this.createNote.bind(this)) // 新增
}

// 新增
createNote(e) {
  var ourNewPost = {
    "title": $(".new-note-title").val(),
    "content": $(".new-note-body").val(),
    "status": "publish"
  }

  $.ajax({
    beforeSend: xhr => {
      xhr.setRequestHeader("X-WP-Nonce", universityData.nonce)
    },
    url: universityData.root_url + "/wp-json/wp/v2/note/", // 不带 ID,代表新建
    type: "POST",
    data: ourNewPost,
    success: response => {
      $(".new-note-title, .new-note-body").val("")
      $(`<li>imagine real data here</li>`).hide().prependTo("#my-notes").slideDown()
      console.log("Congrats")
      console.log(response)
    },
    error: response => {
      console.log("Sorry")
      console.log(response)
    }
  })
}

关键改动点:

  • createNote() 不需要像 updateNote()/deleteNote() 那样先找「点击项所在的 <li>」($(e.target).parents("li")),因为表单是全局唯一的一份,直接用 .new-note-title / .new-note-body 这两个 class 选择器就能唯一定位到输入框
  • 判断「更新」还是「新建」全靠 REST API 的 URL 是否带具体文章 ID:带 ID(/note/58)表示操作那一篇;不带 ID、只到文章类型这一层(/note/)+ POST,WordPress 就理解成要新建一篇
  • status: "publish" 是关键的一步:REST API 新建文章默认状态是 draft(草稿),草稿不会出现在正常查询结果里。这里先手动设成 publish 让新笔记立刻可见;作者提到往后几讲会因为隐私/安全考虑,把笔记的状态改成 private,但这一讲先用 publish 让流程跑通
  • 请求成功后先清空表单两个字段(.val("")),再往 #my-notes 列表顶部插入一个新的 <li>.hide() 先隐藏、.prependTo() 插到列表最前面、再 .slideDown() 滑出,营造一个新笔记从上方展开的动画效果——目前列表项内容还只是占位文字 imagine real data here,格式跟真实笔记条目(大标题、编辑/删除按钮等)还对不上

[截图:前台 My Notes 页面顶部的新建笔记表单(标题输入框、正文文本域、Create Note 按钮)]


Hook / Function 速查

名称类型用途
.prependTo(selector)jQuery 方法把元素插入到目标容器内部的最前面
.slideDown()jQuery 方法用滑动展开动画显示元素,跟 .slideUp() 相反
REST API 文章 status 字段WP REST API 约定字段控制新建/更新的文章状态(draft/publish/private 等),默认新建出来是 draft

常见坑

  • 以为新建成功后文章会自动是 publish 状态——REST API 创建文章默认给的是 draft,草稿不出现在常规查询里,页面上看起来「创建了但好像没生效」,其实是去后台 Notes 列表能看到、只是没发布
  • URL 末尾多带了 ID 或者少一个斜杠——/note/ 代表新建集合、/note/58 代表操作单篇,两者混淆会导致创建变成更新(或反过来报错)

延伸 / 后续讲座会用到

下一讲(part 2)会把「imagine real data here」这个占位文字换成用服务器返回的真实数据(response.idresponse.title.rawresponse.content.raw),并且解决「新建出来的笔记,它的编辑/删除按钮点了没反应」这个问题(因为这些按钮是动态插入的,页面加载时绑定的事件监听器根本不知道它们的存在)。


Sources

Udemy:

  • Become a WordPress Developer: Unlocking Power With Code — Section 19, EP096