簡體   English   中英

如何使用 AJAX 將 div 內容替換為另一個頁面的 div 內容?

[英]How to replace div content with div content of another page using AJAX?

所以我在嘗試讓我的頁面加載看起來更流暢時遇到了問題。 我想要做的是使用 AJAX 從另一個頁面只獲取某個 div,並將此頁面上的一個 div 替換為響應的內容。

這是我的 js 腳本,我使用 AJAX 從不同的頁面獲取一些數據:

$(function() {
    $(".home_nav").click(function() {
        $.ajax({
            type: "GET",
            url: "homepage.php",
            success: function(data) {
                $(".placeholder").html($(data).find(".placeholder").html());
            }
        });
    });
});

其中 placeholder 是兩個頁面上的包裝 div,我只是想刪除此頁面上包含的內容。placeholder 並替換為包含在“homepage.php”中的 contents.placeholder。

jQuery load function 將非常適合這項工作。

有了這個,您可以將數據從 url 加載到指定的占位符中。

在路徑旁邊,您可以指定一個選擇器,它將 select 元素放在請求的頁面上。 在這種情況下p:last-child 在您的情況下,只需將p:last-child替換為.placeholder

看看下面的例子:

 $(".home_nav").click(function() { $('.placeholder').html("Loading..."); $('.placeholder').load('https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/Bio.html p:last-child'); }); $(".home_nav2").click(function() { $('.placeholder2').html("Loading..."); $.ajax({ type: "GET", url: "https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/Bio.html", success: function(data) { var newHtml = $($.parseHTML(data)).filter('p:last-child')[0] $(".placeholder2").html(newHtml); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="home_nav">Learn more (.load)</button> <button class="home_nav2">Learn more (ajax)</button> <div class="placeholder"> <h2>This will be replaced by <kbd>.load()</kbd> function</h2> Pork belly ribeye jowl bacon andouille, pastrami prosciutto hamburger kevin beef ribs. Jerky pork loin frankfurter, ribeye ball tip short ribs salami chicken fatback hamburger beef bresaola picanha. Ground round meatloaf tongue shank hamburger pork loin. Swine corned beef sirloin leberkas, shank hamburger kielbasa pork belly pork loin. </div> <div class="placeholder2"> <h2>This will be replaced by <kbd>ajax()</kbd> function</h2> Pork belly ribeye jowl bacon andouille, pastrami prosciutto hamburger kevin beef ribs. Jerky pork loin frankfurter, ribeye ball tip short ribs salami chicken fatback hamburger beef bresaola picanha. Ground round meatloaf tongue shank hamburger pork loin. Swine corned beef sirloin leberkas, shank hamburger kielbasa pork belly pork loin. </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM