Goodday,
我目前在从客户端向服务器发回XML文件时遇到问题。我使用以下javascript在服务器上发送xml文件的请求:
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
//this function would parse the contents of the xml to the webpage
MyFunction(this);
};
xhttp.open("GET", "Home.xml", true);
xhttp.send();
}

这很有效,我可以成功地将内容解析为我可以在HTML中使用的变量。现在,为了保存我对运行服务器的系统所做的设置,我想发回带有附加值的XML文件。然后,服务器可以将附加的XML文件的内容解析为flash,以便下次在请求时将附加的XML文件发送到客户端。
我发现我可以使用xmlDoc.getElementsByTagName(" tag")[0] .appendChild(node);将节点附加到XML文件中,但我无法理解如何将文件发送回服务器。
我能否以不仅发送请求而是发送XML文件的方式使用xhttp.send()?
提前谢谢。
答案 0 :(得分:0)
好吧,我想通了,并且认为我会为感兴趣的人发布答案。
在我发布问题后,我很快发现了Chris Minnick撰写的以下文章:https://www.webucator.com/how-to/how-send-receive-xml-data-from-the-server.cfm
他的例子使得如何处理通过HTTP POST发送XML数据的事情变得更加清晰。显然,在POST请求的情况下,您可以使用XMLHttpRequest()。send(“您的xml数据”)来发送数据。
我的javascript:
var xml_received = 0;
function loadXMLDoc() {
// Create an XMLHttpRequest object to make a XML document request from server
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "home.xml", true);
// This code listens for a change in the state of xhttp
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
// Request was succesfull so assign the response to the variable we created
xml_received = processXML_index(this);
}
};
// Set request header so the server reads the contents as xml
xhttp.setRequestHeader('Content-Type', 'text/xml');
// Send the request
xhttp.send();
}
function sendXML_index() {
// Create an XMLHttpRequest object to make a XML document request from server
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "", true);
// This code listens for a change in the state of xhttp
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
// Request was succesfull
}
};
// Set request header so the server reads the contents as xml
xhttp.setRequestHeader('Content-Type', 'text/xml');
xml_appended = appendXML(xml_received);
// Send the request
xhttp.send(xml_appended);
}
function processXML_index(xml) {
var xmlDoc = xml.responseXML;
var txt = "";
txt = xmlDoc.getElementsByTagName("palette")[0].childNodes[0].nodeValue;
document.getElementById("demo").innerHTML = txt;
return xmlDoc;
}
function appendXML(xml) {
// currently doesn't append anything but just echoes the xml file
return xml;
}
我编写了函数LoadXMLDoc(),它使用GET请求从服务器加载预定义的XML文件。当请求成功时,函数processXML_index(this)将数据解析到网页并返回xml字符串,然后将其存储在xml_received中。
当我按下网页上的按钮时,会调用SendXML_index()函数。此函数调用appendXML()函数,该函数将接收的XML数据作为参数,并返回附加的(通过网页输入的新值)xml文件(作为字符串)。然后使用xhttp.send(xml_appended)将此字符串发送回服务器。
要将数据附加到XML文件中,您可以使用XMLHttpRequest()。appendChild()。或xmlDoc.getElementsByTagName(“node”)[0] .childNodes [0] .nodeValue =“new content”。