
本文详解如何使用 jquery 的 `.load()` 方法异步刷新页面中某个特定 div 的内容,避免整页刷新,重点解决常见错误(如 jquery 未引入、拼写错误、路径问题),并提供可直接运行的完整示例。
在 Web 开发中,为提升用户体验和减少服务器压力,常需实现“局部刷新”——即仅更新页面中某一块区域(如一个
✅ 正确实现原理
.load() 支持从当前页面(或任意 URL)中提取指定选择器的内容,并将其注入目标元素。语法如下:
$('#targetDiv').load(url + ' #sourceSelector');其中 url + ' #reloadable' 表示:向当前页面(location.href)发起 GET 请求,服务端返回完整 HTML 后,前端仅提取其中 id="reloadable" 的元素内容,替换到当前 #reloadable 元素内。
✅ 完整可运行代码(修正版)
<!DOCTYPE html>
<html>
<head>
<!-- 必须提前引入 jQuery(3.6.0+ 推荐) -->
<script src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
</head>
<body>
<div id="reloadable">
<?php include 'rand.php'; ?>
</div>
<button class="ref" onclick="refreshDiv();">刷新</button>
<script>
function refreshDiv() {
// 关键:使用 location.href + ' #reloadable' 实现同页局部加载
$('#reloadable').load(location.href + ' #reloadable');
}
</script>
</body>
</html>配套 rand.php(确保与 HTML 同目录):
<?php echo rand(0, 10); ?>
⚠️ 常见错误及修复要点
- ❌ jQuery 未引入:.load() 是 jQuery 方法,若未引入 jQuery 库,会报 undefined is not a function 错误。务必在 <script> 使用前引入官方 CDN。</script>
- ❌ 拼写错误:原文本中 <script type="text/<a style=" color: text-decoration:underline title="java" href="https://www.php.cn/zt/15731.html" target="_blank">javacript"> 中 javacript 拼错(应为 <a style="color:#f60; text-decoration:underline;" title= "javascript" href="https://www.php.cn/zt/15724.html" target="_blank">javascript),虽不影响 .load() 执行(因现代<a style="color:#f60; text-decoration:underline;" title= "浏览器" href="https://www.php.cn/zt/16180.html" target="_blank">浏览器忽略错误 type),但属不良实践,建议统一写为 <script>。</script>
- ❌ onclick 绑定冗余:onclick="javascript:refreshDiv()" 中的 javascript: 是协议前缀,非必需;直接写 onclick="refreshDiv()" 更规范。
- ✅ 服务端注意事项:PHP 文件(如 rand.php)需由 Web 服务器(如 Apache/Nginx)解析执行,不可直接双击打开 HTML(否则 PHP 不生效,rand.php 内容将原样显示或报错)。
? 进阶建议
- 若需传递参数(如防缓存、带条件刷新),可改用:
$('#reloadable').load(location.href + ' #reloadable', { t: new Date().getTime() }); - 对于复杂逻辑,推荐封装为独立 AJAX 调用,便于错误处理与加载状态反馈:
function refreshDiv() { $('#reloadable').html('加载中...'); $.get('rand.php') .done(data => $('#reloadable').html(data)) .fail(() => $('#reloadable').html('刷新失败,请重试')); }
通过以上配置,即可稳定实现 #reloadable 区域的无闪屏、无跳转式动态刷新,兼顾简洁性与可靠性。










