如何使用 AJAX 动态更新网页内容而不需要重新加载?

DDD
发布: 2024-10-22 11:18:29
原创
813 人浏览过

How to Update Webpage Content Dynamically Using AJAX Without a Reload?

Change HTML Page Contents Dynamically Without Reloading

You desire to update the contents of a webpage dynamically, specifically a div, without triggering a page refresh. This can be achieved through AJAX (Asynchronous JavaScript and XML).

jQuery Approach

  1. Define JavaScript Function:

    <code class="javascript">function recp(id) {
      $('#myStyle').load('data.php?id=' + id);
    }</code>
    登录后复制
  2. Add Event Handlers:
    Replace the onClick handlers in your HTML with the recp function:

    <code class="html"><a href="#" onClick="recp('1')" &gt; One   &lt;/a&gt;
    <a href="#" onClick="recp('2')" &gt; Two   &lt;/a&gt;
    <a href="#" onClick="recp('3')" &gt; Three &lt;/a&gt;</code>
    登录后复制
  3. Create PHP Script:
    Create a separate PHP file, such as data.php, that handles the data retrieval:

    <code class="php">$id = $_GET['id'];
    $results = mysql_query("SELECT para FROM content WHERE  para_ID='$id'");
    if( mysql_num_rows($results) &gt; 0 )
    {
      $row = mysql_fetch_array( $results );
      echo $row['para'];
    }</code>
    登录后复制
  4. Load Data Dynamically:
    When a link is clicked, the recp function uses AJAX to load the data from data.php into the div with the id 'myStyle':

    <code class="html"><div id='myStyle'&gt;
    &lt;/div&gt;</code>
    登录后复制

Note: Ensure that the path to data.php in the jQuery load() function is correct and that the PHP file has appropriate permissions.

以上是如何使用 AJAX 动态更新网页内容而不需要重新加载?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!