我正在建立一个博客,用户可以在帖子上留言。我使用JavaScript从XML文件中读取数据并将其显示在div元素中。但是,我无法获取页面以将新注释保存到XML文件,然后根据更改的XML文件重写div内容。我知道如何编辑XML文件,但如何保存? (对不起,代码有点乱)
源代码:
的index.html:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<title>Blog</title>
<script src = "loadXML.js">
</script>
<script>
function addComment1(form)
{
var xmlDoc = loadXMLDoc("one.xml");
var use = form.user1.value;
var com = form.comment1.value;
}
</script>
<meta charset = "utf-8"/>
</head>
<body>
<h1>Posts</h1>
<br/>
<!-- A Post -->
<h2>Comments:</h2>
<div>
<p>
<script>
var xmlDoc = loadXMLDoc("one.xml");
var cap = xmlDoc.getElementsByTagName("content");
for (i = 0; i < cap.length; i ++)
{
document.writeln(xmlDoc.getElementsByTagName("user")[i].firstChild.nodeValue + ":<br/>");
document.writeln(xmlDoc.getElementsByTagName("content")[i].firstChild.nodeValue + "<br/><hr/>");
}
</script>
</p>
<form name = "form1">
<input type = "text" name = "user1"/>
<input type = "text" name = "comment1" />
<input type = "submit" value = "Submit" onclick = "addComment1(this.form)"/>
</form>
</div>
</body>
</html>
one.xml:
<?xml version="1.0" encoding="utf-8"?>
<comment>
<user>Gabe Rust</user>
<content>Hello World!</content>
</comment>
loadXML.js:
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
function loadXMLString(txt)
{
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // code for IE
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
return xmlDoc;
}