如何使用 AJAX 動態更新網頁內容而不需要重新載入?
Oct 22, 2024 am 11:18 AMChange 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
-
Define JavaScript Function:
<code class="javascript">function recp(id) { $('#myStyle').load('data.php?id=' + id); }</code>
登入後複製 -
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>
登入後複製 -
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>
登入後複製 -
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中文網其他相關文章!

熱門文章

熱門文章

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)