2017-01-30 72 views
0

我想將html頁面div標籤轉換爲json數據,並將該div附加到另一個html page.get那個使用id的div。html to json獲取div數據

假設存在page.html,其中div標籤在那裏,ID爲page1 page2等。將它們轉換爲json數據並根據它們的id獲取div標籤,然後將這些div標籤附加到page2.html div標籤。怎麼做。

這是page2.html

<div id="page1"> 
this is page1 

</div> 

<div id="page2"> 
this is page1 
</div> 

<div id="page3"> 
this is page1 
</div> 

<div id="page4"> 
this is page1 
</div> 

有div標籤

我試着用js的格但 另一頁是page1.html,並希望訪問DIV page2.html

的獲得
function getdata() 
     { 
      $.get('page2.html', null, function(text){ 
        alert($(text).find('#page1')); 
       }); 
      var json = JSON.stringify(element); 
      alert(json); 
     } 

我試過這個,但它不工作。

+3

檢查下面的代碼尖晶石,請仔細閱讀[MCVE],然後向我們展示的代碼和努力 – mplungjan

+0

可以使用.clone或.html採用div ID並獲得全div標籤的內容並將該內容轉換爲json –

+0

這似乎是一個XY問題。使用ajax這種方式是一種不尋常的且雙重優勢的從外部來源獲取數據的方式。 更好,描述確切的問題。 http://xyproblem.info/ https://en.wikipedia.org/wiki/List_of_Newspeak_words – marmeladze

回答

1

你需要寫在JSON字符串的div對象,轉換成DIV JSON對象的所有必需屬性和值。例如,請參閱下面的代碼段中的 。

function append(){ 
 

 
    var element = document.getElementById("page1"); 
 
    var jsonObject = {}; 
 
    jsonObject.id = element.id; 
 
    jsonObject.innerHTML = element.innerHTML; 
 

 
    var jsonString = JSON.stringify(jsonObject); // this is json for your div. 
 

 
    /// for append div and get div object back from json. 
 
    
 
    var elementProto = JSON.parse(jsonString); 
 
    
 
    var element = document.createElement("DIV"); 
 
    element.innerHTML = elementProto.innerHTML; 
 
    element.id = elementProto.id; 
 
    
 
    
 
    // append to container (in your case its page 1 or 2) 
 
    
 
    document.getElementById("container").append(element); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="page1"> 
 
    <p>this div will appended </p> 
 
</div> 
 

 
<button onclick="append()">append div</button> 
 

 
<div id="container"> 
 

 
</div>

+0

問題ID頁面1在另一個頁面中,而不是在同一頁面 –

+1

獲取div標籤嘗試此$ .get('page2.html',null,function(text){ var wrapper = document.createElement('div' ); wrapper.innerHTML = text; var divElem = wrapper.querySelector(「#page1」); // This is your div }); –

+1

示例plunker https://plnkr.co/edit/fhYRrqTbce3kUmgLIp0n?p=preview –

0

試試這個代碼獲取DIV內容

function getdata() 
    { 
     $.get('page.html', null, function(text){ 
       alert($('#page1').html()); 
      }); 
jsonObj = $('#page1').html(); 
     var obj = $.parseJSON(jsonObj); 
     alert(obj); 
    } 
0

getdata()

jQuery.get('page2.html',null,function(response){ 
    var obj = jQuery('<div/>'); 
    var json = {}; 
    jQuery(obj).append(response); 
    jQuery('[id^="page"]',obj).each(function(index, object){ 
     json[index] = jQuery(object).text(); 
    }); 
    console.log(json); 
}); 
+0

我收到數據,但我只想要div標籤haing id page1的數據,但每個div標籤id id page1 page2 page 3的數據都被追加。 –

+0

我可以改變什麼如果我不想要每個函數 –

+0

如果你想要page1的文本,那麼'jQuery('#page1',obj)'是你的jQuery對象。而不是「每個」循環 –