所以我要做的是将XML数据解析为一个ID为post的新DIV,每次将帖子添加到XML文件(posts.xml)时都会发生这种情况。
我不确定我是否忽视了某些内容,但我无法显示/呈现XML数据。
XML:
<POSTS>
<POST>
<TITLE>Title 123</TITLE>
<AUTHOR>Bob Dylan</AUTHOR>
<CONTENT>BLAH BLAH BLAH</CONTENT>
</POST>
<POSTS>
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Blog</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="posts"></div>
<script src="main.js"></script>
</body>
</html>
Javascript(main.js):
(function () {
// Adds a DOM structure for each post.
function renderPosts(posts) {
// Get the DOM element that will contain the posts.
var postsDiv = document.getElementById("posts");
posts.forEach(function (post) {
// Create the DOM elements.
var postDiv = document.createElement("div"),
postTitleDiv = document.createElement("div"),
postAuthorDiv = document.createElement("div"),
postContentDiv = document.createElement("div");
// Set the content of each element.
postNameDiv.innerHTML = post.name;
postAuthorDiv.innerHTML = post.author;
postContentDiv.innerHTML = post.content;
// Set CSS classes on each div so they can be styled.
postDiv.setAttribute("class", "post");
postNameDiv.setAttribute("class", "post-title");
postAuthorDiv.setAttribute("class", "post-author");
postContentDiv.setAttribute("class", "post-content");
// Assemble the post div.
postDiv.appendChild(postTitleDiv);
postDiv.appendChild(postAuthorDiv);
postDiv.appendChild(postContentDiv);
// Add the post div to the container for posts.
postsDiv.appendChild(postDiv);
});
}
// Fetches the file "posts.xml"
function getPosts(callback){
// Fetch the xml file using XMLHttpRequest.
var request = new XMLHttpRequest();
// When the file has loaded,
request.onload = function () {
// parse the XML text into an array of post objects.
//var posts = XML.parse(request.responseXML);
// Pass the posts array to the callback.
callback(posts);
};
request.open("GET", "posts.xml", false);
request.send();
xmlDoc=xmlhttp.responseXML;
}
// The main program, which gets then renders posts.
getPosts(function (posts) {
renderPosts(posts);
});
}()); //End Main Function