在 Web 开发中,通常需要更新页面的部分内容而不重新加载整个页面。这可以使用 Ajax、PHP 和 jQuery 来实现。
页面包含一个 DIV 元素,其中包含来自数据库的文本和超链接列表。目标是在单击特定链接时将与该链接关联的摘要(文本)加载到 DIV 中。
HTML:
按照描述创建 DIV 和链接元素:
<code class="html"><div id="summary">Here is summary of movie</div> <a href="?id=1" class="movie">Name of movie</a> <a href="?id=2" class="movie">Name of movie</a></code>
JavaScript (jQuery):
处理链接上的点击事件:
<code class="javascript"><script> function getSummary(id) { $.ajax({ type: "GET", url: 'your_php_url', data: "id=" + id, success: function(data) { $('#summary').html(data); } }); } </script></code>
PHP:
在 PHP 文件中处理 GET 请求:
<code class="php">// get the ID from the request $id = $_GET['id']; // fetch the summary from the database $summary = get_summary($id); // return the summary as a string echo $summary;</code>
事件绑定:
添加将 onclick 事件属性传递给链接以调用 getSummary 函数:
<code class="html"><a onclick="getSummary('1')">View Text</a> <div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div></code>
以上是如何使用 Ajax、PHP 和 jQuery 动态更新 DIV 内容?的详细内容。更多信息请关注PHP中文网其他相关文章!