简体   繁体   English

Javascript XMLHTTPRequest不发布XML文件

[英]Javascript XMLHTTPRequest Not Posting XML File

I have a content generator which contians textboxes, textareas and file input controls. 我有一个内容生成器,它包含文本框,textareas和文件输入控件。 All controls are in HTML. 所有控件都是HTML格式。 Once the save button is clicked I create my XML Document with the text entered into the HTML controls. 单击保存按钮后,我使用输入HTML控件的文本创建XML文档。 Finally, I would like the user to be prompted to download the XML File. 最后,我希望提示用户下载XML文件。 I am hoping I can do this using a POST method with a XMLHTTPRequest in Javascript. 我希望我能在Javascript中使用带有XMLHTTPRequest的POST方法来完成此操作。 Once the XML Document is sent with the XMLHTTPRequest here is what happens, 一旦使用XMLHTTPRequest发送XML文档,就会发生这种情况,

Chrome: HTTP Status Code: 304 IE10: Nothing happens Chrome:HTTP状态代码:304 IE10:没有任何反应

Again, I would like the browser to prompt the user to download the XML File. 同样,我希望浏览器提示用户下载XML文件。 Here is my code. 这是我的代码。

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);
            });
        });

I SUPPOSE I SHOULD POST MY XML OUTPUT 我支持我应该发布我的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:\Images\Header.png</imageHeader> 
  <articleImage>C:\Images\Main.png</articleImage> 
  <articleImage2>C:\Images\Deals.png</articleImage2> 
  </images>
  </site>
  </sites>

Try using Filesaver.js to get the user to download a file in memory. 尝试使用Filesaver.js让用户下载内存中的文件。

Look also into Data URI's like this : 还应考虑数据的URI像这样

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

Is there any way to make the browser prompt to download the XML File? 有没有办法让浏览器提示下载XML文件?

Yep. 是的。 Convert your data to Blob , then generate a URL from it, which you can then use in an <a> , give that <a> a download attribute and the browser now knows it's to be saved not opened, then finally simulate a click on it. 将您的数据转换为Blob ,然后从中生成一个URL ,然后您可以在<a>使用,给该<a>一个下载属性,浏览器现在知道要保存未打开,然后最终模拟点击它。 For example; 例如;

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
    )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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