2011-03-01 54 views
1

我正在使用jQuery.load()來加載一個HTML頁面的內容到lightbox中。在這種情況下,最有用的東西是將完整的html頁面轉換爲一個乾淨的html片段,以便插入到頁面中。結合jQuery.load()和ajax dataFilter()

但是(因爲錯誤的第三方API在動態加載時不起作用),我需要先使用正則表達式從頁面中過濾出一個或兩個元素,然後將其作爲html進行處理,這意味着我需要使用$ .ajax的dataFilter選項。

所以,現在我使用的,而不是.load我需要我的過濾文本轉換成乾淨的HTML .load $就自動提供

但是$(響應)產生一個奇怪的越野車jQuery的對象,其中.find(),children()等...不起作用。

誰能告訴我如何得到乾淨的HTML,我需要(我注意到Ajax代碼injQuery有了很大的變化從V 1.4.4到1.5 - 利用溶液兩個版本會做)

這裏是我的迄今(使用jQuery 1.4.4)(參考上面的這段代碼中定義的所有變量和方法)

$.ajax({ 
      url: url, 
      type: "GET", 
      dataType: "html", 
      dataFilter: function (response) { 
       return response.replace(recaptchaRegex, ""); 
      }, 
      success: function (response) { 
       // If successful, inject the HTML into all the matched elements 
       // See if a selector was specified 
       destination.html($(response).children("#lightBoxForm")); 

       callback(); 
      } 
     }); 
+0

你能告訴你什麼加載,過濾,要插入什麼樣的例子嗎? – polarblau 2011-03-05 17:16:22

回答

1

嗯,我看這是前一段時間要求,但希望這將仍然對您有所幫助。從你的問題我明白你想複製與$ .ajax函數的$ .load函數。

您將來可能會發現有用的工具是jQuery source viewer,因此您可以準確瞭解jQuery如何在底層進行操作。

// Using jquery 1.5.1 
    $(function() { 

     var rscript = "/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi"; 

     // Will override all ajax requests on this page including load 
     $.ajaxSetup({ 
      dataFilter: function (response) { 
       return response.replace("Lorem ipsum.", ""); 
      }, 
      type: "GET", 
      dataType: "html", 
      // Disable caching of AJAX responses for example only 
      cache: false 
     }); 

     $("#load").click(function (evt) { 
      evt.preventDefault(); 
      $('#content').load("html.htm #lightBoxForm"); 
     }); 

     $("#ajax").click(function (evt) { 
      evt.preventDefault(); 

      $.ajax({ 
       url: "html.htm", 
       success: function (res) { 
        $("#content").html("#lightBoxForm" ? 
          $("<div>").append(
             res.replace(rscript, "")) 
              .find("#lightBoxForm") : res); 
       } 
      }); 

     }); 

    }); 

而且我的HTML

<input type="button" id="load" value="Load" /> 
    <input type="button" id="ajax" value="Ajax" /> 

    <div id="content"></div> 
+0

事實證明,我所看到的錯誤與加載/ ajax無關,但是爲了努力做到這一點 – wheresrhys 2011-04-06 09:07:44