2017-01-30 51 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对象。而不是“每个”循环 –