简体   繁体   中英

(JS) Generating an XML File To Hold Data on The Fly

I am working on a system that uses JavaScript and XML to store data before it is sent off to a database to be processed. This was done before Ajax really took off so that when clients fill out forms the data entered is stored in a temp server side XML file and then once submitted, the file is sent off to be processed and the data is added to the database without much loading time and therefore works kind of like Ajax.

The primary code in question looks like this:

function makeXML(loc){
    xmlDoc = new ActiveXObject("MSXML2.DOMDocument"); 
    xmlDoc.async = false;

    root = xmlDoc.createElement("root");
    xmlDoc.appendChild(root);

    envelope = xmlDoc.createElement("envelope");
    root.appendChild(envelope);

    packet = xmlDoc.createElement("packet");
    root.appendChild(packet);

    service = server + loc;
}

This works just fine in IE but not at all in chrome because of the use of ActiveXObject("MSXML2.DOMDocument"); which is not supported. In chrome you are meant do something like:

if (window.DOMParser) {//For chrome
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(text, "text/xml");
}
else {// code for IE
    xmlDoc = new ActiveXObject("MSXML2.DOMDocument"); 
    xmlDoc.async = false;
}

The problem now is that the legacy code never actually loaded a physical file it just stored it in memory so I cant use xmlDoc = parser.parseFromString(text, "text/xml"); as it is looking for a physical file.

My question is how do I parse the temp file allowing this function to work in chrome?

Try this:

if (document.implementation.createDocument)
{   
    var xmlDoc = document.implementation.createDocument("", "", null);
    xmlDoc.preserveWhiteSpace = false;
    var parser = new DOMParser();
    xmlDoc = parser.parseFromString(xmlText,"text/xml");
}

If a string is supplied it gets parsed into the var xmlDoc.

Create the document using the DOM implementation api. This is available in all current browsers (including IE) but of course you can use a fallback for older IEs.

var xmlDoc;
if (document.implementation.createDocument) {
  xmlDoc = document.implementation.createDocument("", "", null);
} else {
  xmlDoc = new ActiveXObject("MSXML2.DOMDocument"); 
  xmlDoc.async = false;
}

appendChild() will return the appended node, so you can nest the create call inside the append.

var root = xmlDoc.appendChild(xmlDoc.createElement("root"));

After created the document you can send it using the XMLHTTPRequest without serialization.

xhr.open('post', 'http://someurl');
xhr.send(xmlDoc);

Or serialize it to a string:

var xmlString = (new XMLSerializer()).serializeToString(xmlDoc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM