How to post XML to an iframe with JavaScript

2019-05-30 09:26发布

Basically I want to post XML (with Content-Type text/xml) to an URL and display the output directly in the browser. This has to be done in an iframe.

Is it possible to post the XML to an iframe? In other words, can the Content-Type of the Post-Request be changed to text/xml? PHP4 is also available if necessary.

The URL of the iframe-action has to remain because the Result contains a HTML page with relative links...

1条回答
聊天终结者
2楼-- · 2019-05-30 09:44

It used to be possible to document.open(mimetype) on the iframe back in Netscape, but modern browsers don't support this (and Netscape never supported XML anyway).

In many browsers, you can set an iframe's src to a data URI such as: data:text/xml,%3Celement%3Ehello%3C/element%3E, as long as the document isn't too long. This doesn't work in IE though. So you would need at least a backup plan of going back to the server:

<?php
    header('Content-Type: text/xml');
    echo($_REQUEST('xml'));
?>

Then, if the XML were short enough to fit in a URI, you could set its src via:

iframe.src= 'http://www.example.com/echoxml.php?xml='+encodeURIComponent(xml);

If the XML might be long, you'd need to use a POST request, which means a form submission:

var idoc= iframe.contentDocument || iframe.contentWindow.document; // IE compat
idoc.open();
idoc.write('<form method="post" action="http://www.example.com/echoxml.php">');
idoc.write('    <textarea name="xml"></textarea>');
idoc.write('</form>');
idoc.close();
idoc.getElementsByTagName('textarea')[0].value= xml;
idoc.getElementsByTagName('form')[0].submit();

Is this all worth it? Unless you're using XSL, the unstyled XML view you'd get in most browsers would probably be quite poor. In older/simpler browsers that don't display XML at all you'd just be prompted to download the XML file.

And it's dangerous to allow anyone to inject any XML content into your security context. eg. if they made a return-document containing XHTML scripting content, you'd be vulnerable to cross-site-scripting attacks.

查看更多
登录 后发表回答