首頁 > 後端開發 > php教程 > 如何使用 AJAX 更新動態內容而不刷新頁面?

如何使用 AJAX 更新動態內容而不刷新頁面?

Patricia Arquette
發布: 2024-10-22 11:46:03
原創
983 人瀏覽過

How to Update Dynamic Content without Page Refresh Using AJAX?

Dynamic Content Updates with AJAX

Problem:

You aim to update the content of a div without reloading the page upon clicking a link.

Solution without Refreshing:

Employing AJAX (Asynchronous JavaScript and XML), you can retrieve updated content without reloading the page.

Implementation:

  1. Handle Link Events with JavaScript:

    Assign JavaScript event handlers to links to invoke the data retrieval function.

    <code class="html"><a href="#" onClick="recp('1')" > One   </a></code>
    登入後複製
  2. AJAX Request with jQuery:

    The recp() function uses jQuery's .load() method to retrieve data from a PHP script without reloading the page.

    <code class="javascript">function recp(id) {
      $('#myStyle').load('data.php?id=' + id);
    }</code>
    登入後複製
  3. Retrieve Data with PHP:

    Create a PHP script (e.g., data.php) that retrieves data based on the ID passed in the URL.

    <code class="php"><?php
    require ('myConnect.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. Render Updated Content:

    The retrieved data is loaded into the div with id='myStyle'.

    <code class="html"><div id='myStyle'>
    </div></code>
    登入後複製

With this implementation, clicking links updates the div's content dynamically, providing a seamless and responsive user experience without refreshing the page.

以上是如何使用 AJAX 更新動態內容而不刷新頁面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板