求助:使用jQuery每X秒更新HTML Div区块失效问题排查
问题排查与解决方案
让我来帮你梳理一下为什么你的代码没如期更新内容,以及对应的修复办法:
核心问题分析
你当前的代码逻辑本身没有语法错误,但有几个关键因素导致看起来“没更新”:
用户邮箱在会话中不会自动变化
你的短代码是获取当前登录用户的邮箱,只要用户没注销/切换账号,服务器每次返回的短代码渲染结果都是同一个邮箱地址——所以就算你每3秒重新加载,内容自然不会变,看起来就像没生效。jQuery
load方法的缓存问题
浏览器会对重复的GET请求做缓存,可能导致你的load请求直接读取缓存内容,根本没去服务器重新获取新数据。已弃用的WordPress函数
你用的get_currentuserinfo()已经被WordPress弃用了,虽然暂时可能还能用,但建议替换为官方推荐的wp_get_current_user(),避免后续版本兼容问题。
修复步骤
第一步:修正短代码函数(替换弃用函数)
先把你的短代码函数更新为:
function mm_get_current_user_email(){ $current_user = wp_get_current_user(); // 替代已弃用的get_currentuserinfo() // 先检查用户是否已登录 if ( $current_user->exists() ) { return $current_user->user_email; } // 未登录时返回提示信息 return '当前未登录'; } add_shortcode( 'get_email', 'mm_get_current_user_email');
第二步:解决load的缓存问题
修改JS代码,在请求URL后添加随机参数,强制浏览器跳过缓存:
$(document).ready(function(){ setInterval(function(){ // 添加时间戳作为随机参数,避免浏览器缓存请求结果 $("#here").load(window.location.href + " #here?_=" + new Date().getTime() ); }, 3000); });
第三步:测试更新机制是否正常
如果你想验证更新逻辑确实在工作,可以临时把短代码改成返回当前时间,这样每3秒就能看到内容变化:
function mm_get_current_user_email(){ return date('Y-m-d H:i:s'); } add_shortcode( 'get_email', 'mm_get_current_user_email');
测试没问题后,再改回邮箱逻辑即可。
更高效的优化方案(推荐)
其实你不需要每次加载整个页面的片段,用WordPress AJAX接口只请求邮箱数据会更高效:
注册AJAX接口
在主题的functions.php中添加:// 登录用户可访问的AJAX接口 add_action('wp_ajax_get_current_user_email', 'mm_ajax_get_current_user_email'); // 未登录用户可访问的AJAX接口(如果需要开放给游客) add_action('wp_ajax_nopriv_get_current_user_email', 'mm_ajax_get_current_user_email'); function mm_ajax_get_current_user_email(){ $current_user = wp_get_current_user(); if ( $current_user->exists() ) { wp_send_json_success( $current_user->user_email ); } else { wp_send_json_error( '当前未登录' ); } }前端AJAX请求代码
替换原来的JS代码为:$(document).ready(function(){ // 定义更新邮箱的函数 function updateUserEmail(){ $.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'POST', data: { action: 'get_current_user_email' // 和后端注册的接口名对应 }, cache: false, // 禁用缓存 success: function(response){ if (response.success) { $("#here").text(response.data); } else { $("#here").text(response.data); } } }); } // 页面加载时先获取一次 updateUserEmail(); // 每3秒自动更新 setInterval(updateUserEmail, 3000); });
这个方案只请求必要的邮箱数据,比加载整个页面片段更轻量,也更符合WordPress的开发规范。
内容的提问来源于stack exchange,提问作者aser23
相关产品推荐
相关产品推荐

