首页 > 解决方案 > 如何从mysql获取php上的XML字符串并将其传递给java脚本

问题描述

所以我得到了这个代码:

                  <input type='button' value='clickme' onclick='download(\"" . $rowtable['Protocolo'] . ".xml\",\"" . $rowtable['XML']. "\");'/></input>
                  <script>
                  function download(filename, text) {
                    var pom = document.createElement('a');
                    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
                    pom.setAttribute('download', filename);
                
                    if (document.createEvent) {
                        var event = document.createEvent('MouseEvents');
                        event.initEvent('click', true, true);
                        pom.dispatchEvent(event);
                    }
                    else {
                        pom.click();
                    }
                }
                  </script>

它从我的数据库中获得 2 个结果,即字符串(协议)和文本(XML)。但问题是我的 TEXT(XML) 数据如下所示:

<?xml version="1.0" encoding="UTF-8"?><enviNFe versao="4.00" xmlns="asdasdasdasdasd"><idLote>1</idLote><indSinc>1</indSinc><NFe xmlns="asdsdasadsad">

正如你所看到的,它上面有很多“。而且它是一种错误,代码。所以我的问题是,我怎样才能将所有这些 $rowtable['XML'] 转换为正确的字符串。所以我可以将它传递给JS,所以我可以下载它。

如果您有更好的方法从我的数据库下载此 XML 数据,也欢迎。

标签: javascriptphpxmlstringdownload

解决方案


您可以使用 对 php 中的 xml 进行编码urlencode,并直接在 javascript 中使用它的值。

<input type='button' value='clickme' onclick='download(\"" . $rowtable['Protocolo'] . ".xml\",\"" . urlencode($rowtable['XML']). "\");'/></input>
<script>
function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + text);
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}
</script>

推荐阅读