优化AJAX删除请求代码:消除自定义文章类型的代码重复
解决方案:动态读取自定义文章类型,复用删除AJAX代码
核心思路是把自定义文章类型(CPT)的slug存储在文章卡片的data属性中,点击删除按钮时读取这个值,动态拼接REST API请求URL,彻底避免重复代码。
步骤1:修改文章卡片的HTML结构
在渲染每个文章卡片时,添加data-post-type属性,值为当前文章对应的CPT slug(即REST API URL里的标识,比如properties-for-sale、post-type-1)。
如果是WordPress模板渲染,直接用PHP函数获取当前文章类型:
<div class="agent-dashboard-listing-card" data-id="<?php echo get_the_ID(); ?>" data-post-type="<?php echo get_post_type(); ?>"> <!-- 卡片内容 --> <button class="delete-listing-btn">删除文章</button> </div>
如果是静态HTML,手动给对应卡片添加属性:
<div class="agent-dashboard-listing-card" data-id="456" data-post-type="post-type-2"> <button class="delete-listing-btn">删除文章</button> </div>
步骤2:优化AJAX代码(仅需一份)
修改原JS代码,读取data-post-type的值动态拼接URL,同时优化逻辑提升稳定性:
jQuery(".delete-listing-btn").on("click", function(e) { // 匹配最近的父级卡片,避免多层级匹配问题 const thisPost = jQuery(e.target).closest(".agent-dashboard-listing-card"); const postId = thisPost.data('id'); const postType = thisPost.data('post-type'); // 基础校验,防止无效请求 if (!postId || !postType) { alert("无法获取文章信息,请刷新页面重试"); return; } jQuery.ajax({ beforeSend: (xhr) => { xhr.setRequestHeader('X-WP-Nonce', msSiteData.nonce); }, // 用模板字符串动态拼接URL,更易读 url: `https://mallorca-select.com/wp-json/wp/v2/${postType}/${postId}`, type: 'DELETE', success: function () { alert("文章删除成功!"); // 可选:删除成功后移除卡片,提升用户体验 thisPost.fadeOut(() => thisPost.remove()); }, error: function (request, error) { console.error("删除失败详情:", request); alert(`删除失败:${error}`); } }); });
关键优化点说明
closest()替代parents():仅匹配最近的父级卡片元素,比parents()更高效,不会误匹配上层无关元素- 动态读取CPT:通过
data-post-type直接获取当前文章类型,无需为每个CPT单独写逻辑 - 基础校验:避免因data属性缺失导致的无效API请求
- 模板字符串拼接:比传统字符串拼接更直观,减少语法错误
- DOM移除优化:删除成功后即时移除卡片,让用户直观看到操作结果
内容的提问来源于stack exchange,提问作者Gabriele Cettolin
相关产品推荐
相关产品推荐

