基本上,我有一个文本框,在其中输入URL,然后单击“确定”按钮,它将在页面左侧显示HTML的预览;右侧将具有HTML标记(正文,标题,div,span等)的树状 View ,该标记在HTML中用作附加图像。预期的JSON结果应在此问题的结尾。我无法遍历JSON并创建树。我尝试了以下方法:
HTML和JS代码:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ABC</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>
<body>
<div id="wrapper">
<header>
<h1 class="logo"><img src="images/logo.png" alt="" title="" /></h1>
</header>
<div id="container">
<div class="search-box">
<input type="text" id="url" value="" class="txt-box" />
<input type="button" value="OK" class="btn-search" />
</div>
<div class="inner-wrap">
<div class="left-wrap" id="preview-sec">
</div>
<div class="right-wrap" id="tree-sec">
</div>
</div>
</div>
</div>
<script type="text/javascript" language="javascript" src="js/jquery-1.11.1.js"></script><!-- Jquery plugin -->
<script>
var counter = 0;
$(document).ready(function(){
$('.btn-search').click(function(){
if ($('#url').val() != '') {
$.get(
'http://localhost/test/getHTML.php', {url:$('#url').val()},
function(response) {
$('#preview-sec').html(response);
},'html');
$.getJSON('http://localhost/test/results.json', function(json) {
traverse(json,0);
});
}
});
});
function traverse(obj,id){
if (typeof(obj)=="object") {
if (id == 0) {
$('#tree-sec').append('<ul></ul>');
} else {
$(id).append('<ul></ul>');
}
$.each(obj, function(i,val){
if (i != 'attributes' && i != 'value') {
counter += 1;
var li_populate = "<li id="+i+"-"+counter+">"+i+"</li>";
if (id == 0) {
$('#tree-sec ul').append(li_populate);
} else {
$(id).find('ul').append(li_populate);
}
traverse(val,"#"+i+"-"+counter);
}
})
}
}
</script>
</body>
</html>
PHP代码:
<?php
$url = $_GET['url'];
$html = file_get_contents($url);
function html_to_obj($html) {
$dom = new DOMDocument();
$dom->loadHTML($html);
return element_to_obj($dom->documentElement);
}
function element_to_obj($element) {
//print_r($element);
$obj = array();
$attr = array();
$arr = array();
$name = $element->tagName;
foreach ($element->attributes as $attribute) {
$attr[$attribute->name] = $attribute->value;
if ($attribute->name == 'id') {
$name .= '#'.$attribute->value;
}
}
if (!empty($attr)) {
$arr["attributes"] = $attr;
}
if ($element->nodeValue != '') {
$arr["value"] = $element->nodeValue;
}
foreach ($element->childNodes as $subElement) {
if ($subElement->nodeType == XML_TEXT_NODE) {
}
elseif ($subElement->nodeType == XML_CDATA_SECTION_NODE) {
}
else {
$arr["child_nodes"][] = element_to_obj($subElement);
}
}
$obj[$name] = $arr;
return $obj;
}
$json = json_encode(html_to_obj($html));
$fp = fopen('results.json', 'w');
fwrite($fp,$json);
fclose($fp);
echo $html;exit();
?>
JSON树输出:
JSON结果:
{
"html": {
"attributes": {
"lang": "en"
},
"value": "Test Development Test\r\n *{\r\n box-sizing:border-box;\r\n }\r\n body {\r\n margin:0;\r\n font-family: sans-serif;\r\n color: #999;\r\n }\r\n a, a:visited {\r\n text-decoration:none;\r\n }\r\n .movie-list .movie{\r\n width:250px;\r\n float:left;\r\n margin-right:25px;\r\n }\r\n .movie-list .movie img{\r\n width:100%;\r\n }\r\n .movie-list .movie a.title{\r\n text-decoration:none;\r\n color:#999;\r\n font-weight:bold;\r\n font-size:18px;\r\n line-height:25px;\r\n }\r\n .movie-list .movie .synopsis{\r\n font-size:14px;\r\n line-height:20px;\r\n }\r\n",
"child_nodes": {
"head": {
"child_nodes": {
"meta": {
"attributes": {
"name": "description",
"content": "A ast of animated movies"
}
},
"title": {
"value": "Test Development Test"
},
"style": {
"attributes": {
"type": "text/css"
},
"value": "\r\n *{\r\n box-sizing:border-box;\r\n }\r\n body {\r\n margin:0;\r\n font-family: sans-serif;\r\n color: #999;\r\n }\r\n a, a:visited {\r\n text-decoration:none;\r\n }\r\n .movie-list .movie{\r\n width:250px;\r\n float:left;\r\n margin-right:25px;\r\n }\r\n .movie-list .movie img{\r\n width:100%;\r\n }\r\n .movie-list .movie a.title{\r\n text-decoration:none;\r\n color:#999;\r\n font-weight:bold;\r\n font-size:18px;\r\n line-height:25px;\r\n }\r\n .movie-list .movie .synopsis{\r\n font-size:14px;\r\n line-height:20px;\r\n }\r\n"
}
}
},
"body": {
"child_nodes": {
"h1": {
"value": "List of animated movies"
},
"div": {
"attributes": {
"class": "movie-list"
},
"child_nodes": {
"div#bh_6": {
"attributes": {
"class": "movie",
"id": "bh_6",
"data-year": "2014"
},
"child_nodes": {
"img": {
"attributes": {
"src": "http://ia.media-imdb.com/images/M/MV5BMjI4MTIzODU2NV5BMl5BanBnXkFtZTgwMjE0NDAwMjE@._V1_SY317_CR0,0,214,317_AL_.jpg"
}
},
"a": {
"attributes": {
"class": "title",
"href": "http://www.imdb.com/title/tt2245084/"
},
"value": "Big Hero 6"
},
"div": {
"attributes": {
"class": "synopsis"
},
"value": "The special bond that develops between plus-sized inflatable robot Baymax, and prodigy Hiro Hamada, who team up with a group of friends to form a band of high-tech heroes."
}
}
},
"div#tlm": {
"attributes": {
"class": "movie",
"id": "tlm",
"data-year": "2014"
},
"child_nodes": {
"img": {
"attributes": {
"src": "http://ia.media-imdb.com/images/M/MV5BMTg4MDk1ODExN15BMl5BanBnXkFtZTgwNzIyNjg3MDE@._V1_SX214_AL_.jpg"
}
},
"a": {
"attributes": {
"class": "title",
"href": "http://www.imdb.com/title/tt1490017/"
},
"value": "The Lego Movie"
},
"div": {
"attributes": {
"class": "synopsis"
},
"value": "An ordinary Lego construction worker, thought to be the prophesied 'Special', is recruited to join a quest to stop an evil tyrant from gluing the Lego universe into eternal stasis."
}
}
},
"div#httyd": {
"attributes": {
"class": "movie",
"id": "httyd",
"data-year": "2010"
},
"child_nodes": {
"img": {
"attributes": {
"src": "http://ia.media-imdb.com/images/M/MV5BMjA5NDQyMjc2NF5BMl5BanBnXkFtZTcwMjg5ODcyMw@@._V1_SX214_AL_.jpg"
}
},
"a": {
"attributes": {
"class": "title",
"href": "http://www.imdb.com/title/tt0892769/"
},
"value": "How to Train Your Dragon"
},
"div": {
"attributes": {
"class": "synopsis"
},
"value": "A hapless young Viking who aspires to hunt dragons becomes the unlikely friend of a young dragon himself, and learns there may be more to the creatures than he assumed."
}
}
},
"div#up": {
"attributes": {
"class": "movie",
"id": "up",
"data-year": "2009"
},
"child_nodes": {
"img": {
"attributes": {
"src": "http://ia.media-imdb.com/images/M/MV5BMTk3NDE2NzI4NF5BMl5BanBnXkFtZTgwNzE1MzEyMTE@._V1_SX214_AL_.jpg"
}
},
"a": {
"attributes": {
"class": "title",
"href": "http://www.imdb.com/title/tt1049413/"
},
"value": "Up"
},
"div": {
"attributes": {
"class": "synopsis"
},
"value": "By tying thousands of balloons to his home, 78-year-old Carl sets out to fulfill his lifelong dream to see the wilds of South America. Russell, a wilderness explorer 70 years younger, inadvertently becomes a stowaway."
}
}
},
"div#mi": {
"attributes": {
"class": "movie",
"id": "mi",
"data-year": "2001"
},
"child_nodes": {
"img": {
"attributes": {
"src": "http://ia.media-imdb.com/images/M/MV5BMTY1NTI0ODUyOF5BMl5BanBnXkFtZTgwNTEyNjQ0MDE@._V1_SX214_AL_.jpg"
}
},
"a": {
"attributes": {
"class": "title",
"href": "http://www.imdb.com/title/tt0198781/"
},
"value": "Monsters, Inc."
},
"div": {
"attributes": {
"class": "synopsis"
},
"value": "Monsters generate their city's power by scaring children, but they are terribly afraid themselves of being contaminated by children, so when one enters Monstropolis, top scarer Sulley finds his world disrupted."
}
}
}
}
}
}
}
}
}
}
最佳答案
根据您的问题,遍历返回的json对象并创建树的部分是有问题的。在您的代码中,遍历json数据的递归函数在生成ul
代码时遇到了一些小问题。返回对象的结构使其更具挑战性。
我能够稍微修改您的html/javascript
代码(无需过多更改)以打印出树。下面的相关代码:
CSS:
div#tree-sec ul ul{
margin-left: 25px;
}
div#tree-sec ul li{
color: #666;
}
div#tree-sec ul a{
color: #111;
text-decoration: underline;
cursor: pointer;
}
div#tree-sec ul a:hover {
text-decoration: none;
}
div#tree-sec ul.collapsible{
/* Custom parent styles here... */
/* Such as a folder icon or 'plus' sign */
}
HTML和JS:
...
...
<div class="inner-wrap">
<div class="left-wrap" id="preview-sec">
<iframe id="preview"></iframe>
</div>
<div class="right-wrap" id="tree-sec">
<ul id="treehtml1"></ul>
</div>
</div>
....
....
<script type="text/javascript">
var counter = 0;
$(document).ready(function(){
$('.btn-search').click(function(){
if ($('#url').val() != '') {
$.get('http://localhost/test/getHTML.php', {url:$('#url').val()}, function(response) {
$('#preview-sec').html(response);
},'html');
$.getJSON('http://localhost/test/results.json', function(json) {
if(typeof(json) == "object"){
traverse(json,'html',1);
makeCollapsible();
}
});
}
});
});
function traverse(obj, element, counter){
for (var i in obj){
$("#tree"+element+counter).append("<li id='"+i+counter+"'>"+i+"</li>"); // Add element to the tree
if(obj[i].hasOwnProperty('child_nodes')){
$("#"+i+counter).append("<ul id='tree"+i+(counter+1)+"'></ul>"); // If there are children, add a parent ul and pass the name to subsequent recursive calls for each child
for(var j in obj[i].child_nodes){
traverse(obj[i].child_nodes[j], i, counter + 1); // Recursive call to add child
}
}
}
}
function makeCollapsible(){
$('ul.parent').each(function(i) {
var parent_li = $(this).parent('li');
parent_li.addClass('collapsible'); //Use this selector to style your parent items...
// Temporarily remove the list from the
// parent list item, wrap the remaining
// text in an anchor, then reattach it.
var sub_ul = $(this).remove();
parent_li.wrapInner('<a/>').children('a').click(function() {
// Toggle the children...
sub_ul.toggle();
});
parent_li.append(sub_ul);
});
// Hide all lists except the outermost.
$('ul ul').hide();
}
</script>
....
....
这应该提供一个正确嵌套的基于
ul
的树。如果很难创建树的图像,那么最好是正确设置生成的ul
代码片段的样式,在服务器上用它创建一个html页面,然后使用服务器端工具,例如wkhtmltoimage from the wkhtmltopdf package将html文档渲染为图像。另外,我想提到的另一件事是,我建议您使用
iframe
而不是将检索到的html加载到div中,因为那样,检索到的html不会干扰您的当前页面。在上面的示例中,我在预览iframe
中添加了div
。在这种情况下,您可以使用php仅输出json
数据,并将iframe
设置为预览url就像将url分配为src
的iframe
属性一样简单。像这样:$("#preview").prop("src", $("#url").val())
。编辑:
更新了带有修复程序的代码。还添加了一个新的js函数
makeCollapsible()
,以根据OP的注释将ul
追溯转换为可单击的可折叠树结构。还添加了相关的CSS
样式来设置树结构的样式。现在,这棵树对我来说就像下面的图片: