簡體   English   中英

在AJAX調用中加載HTML

[英]Load HTML within AJAX call

我在編寫Javascript函數時遇到一些困難。 腳本的基本功能是,當調用特定的AJAX函數並成功返回時,它將從文件中加載一些HTML,並將該HTML插入首頁中的HTML中,然后(一旦加載)在父div中淡出。

    jQuery.ajax({
    type: "POST",
    url: "fns/authenticate.php",
    data: dataString,
    success: function (data) {
        if (data=='1') {
            jQuery("#authlogin").fadeOut(500, function(){
                $(this).remove();                   
                jQuery("#result").load("fns/logic.html", function() {
                    jQuery('#authtrue').fadeIn(1000);
                });
        });
        } else {
            jQuery('#details-error').fadeIn(200);
        }
    }
});

return false;

現在,AJAX似乎可以正常運行,因為它將在正確的條件下執行並逐漸消失,並在正確的div中出現,問題似乎出在,該內容不是從logic.html加載的,還是沒有綁定到#result div正確。

主頁的html如下所示:

<div id="authlogin">
<!-- HTML form -->
</div>

<div id="authtrue" style="display: none;">
<div id="result"></div>
</div>

任何幫助將非常感激。

這是您必須解決自己的問題之一,因為我們無權訪問您的fns/logic.html ,因此無法進行全面測試。

但是,有些想法:

(1) .load()成功函數的基本邏輯似乎正確。 這是一個jsFiddle ,它近似於AJAX成功函數的邏輯。 我將.html()替換為.load .load()因為jsFiddle無法執行Ajax。 無論如何,假設.load()正在做應做的事情,那么該部分應該可以正常工作。

(2)您可能已經知道這一點,但是請注意.load()$.ajax()簡寫.post().get() 隨着代碼塊的結構化,您可能會發現$.ajax()易於排除故障。 通常,對速寫結構進行故障排除比對$.ajax()故障排除更加抽象/困難。

(3)使用Chrome中的開發人員工具(按F12鍵),以驗證logic.html的內容已插入#result div中。 您可能會發現,就像我在玩jsFiddle時所做的那樣,已注入了內容,但#authtrue div仍然隱藏。 至少您會知道已經找到了logic.html文檔並插入了內容。 確切地知道問題出在哪里,查找/修復其余問題現在可能變得微不足道了。

(4)您的logic.html文件是否包含不必要的頭信息? 如果是這樣,您可以僅通過插入文檔的主體或包含div的頂層將其刪除。 請參閱 jQuery文檔的這一部分

jQuery("#result").load("fns/logic.html #container", function() {//CALLBACK IN HERE});

(5)使用多種方法創建一個僅加載,僅加載logic.html文檔的測試文檔是一個明智的主意:

方法A:使用PHP(或您使用的任何服務器端語言)

<div id="authlogin">
    <!-- HTML form -->
    <input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
    <div id="result"><?php include 'logic.html'; ?></div>
</div>

方法B:使用load()

HTML:

<div id="authlogin">
    <!-- HTML form -->
    <input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
    <div id="result"></div>
</div>

jQuery的:

jQuery('#authtrue').show();
jQuery("#result").load("fns/logic.html");

(6)確保目標元素jquery選擇器中If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent.錯字: If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent.選擇器If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent. 來自文檔

在這里所有人的幫助下,我自己設法解決了這個問題。 最終成為瀏覽器緩存問題。 一旦我清除了緩存,一切就神奇地工作了。

暫無
暫無

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

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