2012-03-31 16 views
42

可變我知道我可以在HTML中加載到一個div:如何加載HTML與jQuery的

$("#my_div").load("http://www.mypage.com"); 

,但我想要做的是負荷的html到像一個變量:

my_var = load("http://www.mypage.com"); 

任何幫助都很好。

我想環路儘管一些項目,如:

HLS.functions.LoadSideModules = function() { 
    HLS.sideModuleContent = new Object(); 
    for(var i = 0; i < HLS.currentModuleConfig.POLICIES.POLICY.length; i++) { 
     for(var y = 0; y < HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE.length; y++) { 
      for(var POS in HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE[y]) { 
       var item = HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE[y][POS]; 
       if(!HLS.sideModuleContent[item]) { 
        HLS.sideModuleContent[item] = j.get(HLS.config.K2GETMODULE + HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE[y][POS]); 
       } 
      } 
     } 
    } 
}; 

回答

68
$.get("http://www.mypage.com", function(my_var) { 
    // my_var contains whatever that request returned 
}); 

底下jQuery將推出其觸發給定的URL的Ajax請求。它還試圖智能地猜測哪些數據將被接收(如果它是有效的html,則不需要指定)。如果您需要獲得另一種數據類型只是傳遞,在作爲最後一個參數,例如

$.get("http://www.mypage.com", function(my_var) { 
    // my_var contains whatever that request returned 
}, 'html'); // or 'text', 'xml', 'more' 

參考:.get()

+0

它適用於我,但在加載後在控制檯顯示錯誤:「Uncaught SyntaxError:Unexpected token <」。任何想法爲什麼? – 2015-04-03 07:56:52

26

你可以在內存上也創建一個元素,並使用load()方法:

var $div = $('<div>'); 

$div.load('index.php #somediv', function(){ 
    // now $(this) contains #somediv 
}); 

的優點是,可以指定通過在創建一個新的元件使用的選擇器(#somediv)

1

加載其中的index.php要部是一種選擇,你也可以克隆任何元素。正如它所說的,它複製了所有的舊節點的屬性和值,'精確克隆'。

如果您只需要複製html的特定部分,這也提供了靈活性來填充來自抓取頁面的特定元素層次結構(即,包括所有兒童)內的所有內容。

例如,如果層次結構是 -

<div id='mydiv'> 
    <div> 
     <span> 
     ...</span> 
    </div> 
</div> 

//... 

var oldElement = document.getElementById('mydiv'); 
var newElement = oldElement.cloneNode(true); 

/* #selector selects only that particular section & the '> *' enables to copy all of the child nodes under the parent #selector 
Replace URL with the required value 
function specification is optional... */ 

jQuery(newElement).load(URL+'#selector > *'[,function(response, status, xhr){}]); 

//... 

現在,只要你想(使用原生的JavaScript爲好,因爲它是一個天然的元素),您可以編程方式處理該變量爲newElement。

1
function includeHTML_callBack(result){ 
     var my_var = result; 
    } 

    function includeHTML(link, callBack) { 
      var xhttp = new XMLHttpRequest(); 
      xhttp.onreadystatechange = function() { 
      if (this.readyState == 4 && this.status == 200) { 
       callBack(this.responseText); 
      } 
      }  
      xhttp.open("GET", link, true); 
      xhttp.send(); 
      return; 
    } 

    includeHTML("http://www.mypage.com", includeHTML_callBack);