You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery通过按钮点击重载远程文件中的div元素(非定时)

解决手动点击按钮更新指定PHP页面内容的问题

你的需求是通过declarator.php中的按钮手动触发,更新index.php里id="content"的div内容,下面给出可行的修正方案:

问题分析

现有代码的核心问题:如果declarator.php是独立页面,页面内不存在id="content"的元素,调用$('#content').load(...)会无法执行;另外,直接加载index.php #content时,浏览器可能缓存旧内容,导致无法获取最新数值。

修正方案

1. 页面结构调整(常用场景)

如果希望在展示内容的index.php页面内放置更新按钮,需要在index.php中引入declarator.php的内容:

index.php

<div class="container" id="content">
<?php print $rs['current_number']; ?>
</div>

<?php include 'declarator.php'; ?>

2. 修正declarator.php的JS代码

调整JS逻辑,添加缓存处理和错误回调,确保请求能获取最新内容:

declarator.php

<head>
    <title></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
          $('#reloader').click(function() {
            // 添加时间戳参数避免浏览器缓存旧内容
            var targetUrl = 'index.php #content?' + new Date().getTime();
            console.log('正在加载最新数值');
            // 加载目标内容并处理异常
            $('#content').load(targetUrl, function(response, status, xhr) {
                if (status === "error") {
                    console.log('加载失败: ' + xhr.status + ' ' + xhr.statusText);
                }
            });
          });
        });
    </script>
</head>
<body>
<button id="reloader" type="button"> 更新数值 </button>
</body>

3. 性能优化建议

如果后续逻辑复杂,可以单独写一个轻量化接口返回数值,避免加载整个页面内容:

新建get_current_number.php

<?php
// 这里写入获取$rs['current_number']的逻辑(比如数据库查询)
echo $rs['current_number'];
?>

然后修改declarator.php中的JS代码:

$('#content').load('get_current_number.php?' + new Date().getTime());

内容的提问来源于stack exchange,提问作者Aris Espiritu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 05:07:40