Javascript XMLHTTPRequest Not Posting XML File



我有一个内容生成器,它控制文本框,文本区域和文件输入控件。所有控件都采用 HTML 格式。单击保存按钮后,我使用输入到 HTML 控件中的文本创建我的 XML 文档。最后,我希望提示用户下载XML文件。我希望我可以使用带有Javascript中的XMLHTTPRequest的POST方法来做到这一点。一旦XML文档与XMLHTTPRequest一起发送,就会发生以下情况,

Chrome:HTTP 状态代码:304IE10:没有任何反应

同样,我希望浏览器提示用户下载XML文件。这是我的代码。

function generateBaseNodes() {
            var xmlString = '<?xml version="1.0"?>' +
                    '<sites>' +
                    '<site>' +
                    '<textareas>' +
                    '</textareas>' +
                    '<textboxes>' +
                    '</textboxes>' +
                    '<images>' +
                    '</images>' +
                    '</site>' +
                    '</sites>';
            if (window.DOMParser) {
                parser = new DOMParser();
                xmlDocument = parser.parseFromString(xmlString, "text/xml");
            }
            else // Internet Explorer
            {
                xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
                xmlDocument.async = false;
                xmlDocument.loadXML(xmlString);
            }
            return xmlDocument;
        }
        function saveXmlFile(xmlDocument) {
            if (window.XMLHttpRequest) { // IE7+, Chrome. Firefox, Opera. Safari
                xmlhttp = new XMLHttpRequest();
            }
            else { // IE5 & IE6
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.open('POST', 'http://localhost:57326/ContentGenerator.html', true);
            xmlhttp.setRequestHeader('Content-type','text/xml');
            xmlhttp.send(xmlDocument);
        }
        $('document').ready(function () {
            $('#templateTab a').click(function (e) {
                e.preventDefault()
                $(this).tab('show')
            })
            //Create TextArea XML elements and add them
            $('#btnSave').click(function () {
                var x;
                var xmlDocument = generateBaseNodes();
                $('.content').each(function () { // Textarea
                    if ($(this).attr('id') != undefined) {
                        if ($(this).is('textarea')) {
                            // create article node with control id.
                            articleNode = xmlDocument.createElement($(this).attr('id'));
                            // append node to xmldocument
                            x = xmlDocument.getElementsByTagName('textareas')[0];
                            x.appendChild(articleNode);
                            // append text
                            articleNode.appendChild(xmlDocument.createTextNode($(this).text()));
                        }
                        if ($(this).is('input[type=text]')) { // Textbox
                            textNode = xmlDocument.createElement($(this).attr('id'));
                            x = xmlDocument.getElementsByTagName('textboxes')[0];
                            x.appendChild(textNode);
                            textNode.appendChild(xmlDocument.createTextNode($(this).text()));
                        }
                    } else { // Show error if a control does not have an ID assigned to it.
                        alert('The' + $(this).prop('type') + 'has an undefined ID.');
                    }
                });
                $('.imageContent').each(function () {
                    if ($('.imageContent input[type=file]')) {  // Image url
                        // Validate file is an image
                        switch ($(this).val().substring($(this).val().lastIndexOf('.') + 1).toLowerCase()) {
                            case 'gif': case 'jpg': case 'png':
                                imageNode = xmlDocument.createElement($(this).attr('id'));
                                x = xmlDocument.getElementsByTagName('images')[0];
                                x.appendChild(imageNode);
                                imageNode.appendChild(xmlDocument.createTextNode($(this).val()));
                                break;
                            default:
                                $(this).val('');
                                // error message here
                                alert("not an image");
                                break;
                        }
                    }
                });
                saveXmlFile(xmlDocument);
            });
        });

我想我应该发布我的 XML 输出

<sites>
 <site>
 <textareas>
  <article1>sfdsfd</article1> 
  <article2>dsfsdf</article2> 
  </textareas>
 <textboxes>
  <title>dsfdsf</title> 
  <contentHeader>sdfsdf</contentHeader> 
  <linkContent>sdf</linkContent> 
  <link>sdfsd</link> 
  <relatedContent>sdfsdf</relatedContent> 
  <contentLink>dsf</contentLink> 
  <relatedArticle>sdfa</relatedArticle> 
  <articleLink>sfdf</articleLink> 
  </textboxes>
 <images>
  <imageHeader>C:ImagesHeader.png</imageHeader> 
  <articleImage>C:ImagesMain.png</articleImage> 
  <articleImage2>C:ImagesDeals.png</articleImage2> 
  </images>
  </site>
  </sites>

有没有办法让浏览器提示下载XML文件?

是的。将数据转换为 Blob,然后从中生成一个 URL,然后可以在<a>中使用它,为该<a>提供一个下载属性,浏览器现在知道它要保存而不是打开,最后模拟单击它。例如;

function txtToBlob(txt) {
    return new Blob([txt], {type: 'plain/text'});
}
function genDownloadLink(blob, filename) {
    var a = document.createElement('a');
    a.setAttribute('href', URL.createObjectURL(blob));
    a.setAttribute('download', filename || '');
    a.appendChild(document.createTextNode(filename || 'Download'));
    return a;
}
function downloadIt(a) {
    return a.dispatchEvent(new Event('click'));
}
// and use it
var myText = 'foobar',
    myFileName = 'yay.txt';
downloadIt(
    genDownloadLink(
        txtToBlob(myText),
        myFileName
    )
);

尝试使用 Filesaver.js 让用户下载内存中的文件。

还可以像这样查看数据 URI:

<a href="data:application/octet-stream;charset=utf-8;base64,Zm9vIGJhcg==">text file</a>

相关内容

最新更新