gpt4 book ai didi

javascript - IE 中未定义的 outerHTML

转载 作者:数据小太阳 更新时间:2023-10-29 04:31:48 24 4
gpt4 key购买 nike

我的代码从 Ajax 调用中获取 JSON,其中包含 XML,并通过它读取一些信息。

虽然 XML 的解析在 Chrome 中运行良好,但在 IE 中却不行,因为在 IE 中 outerHTML 返回 undefined

我浏览了几篇文章并尝试了几种可能的解决方案,但都没有成功。

JavaScript 代码是:

$.ajax({
url: 'getJSONwithXML.do',
type:'POST',
data:'',
dataType: 'json',
cache: false
}).done(function(data) {
var jsonResp = JSON.parse(data.data.respuesta);
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(jsonResp,"text/xml");
var texto = $(xmlDoc).find('texto').prop('outerHTML');
console.log(texto); // <--- undefined in IE
$('body').append('<div>' + texto + '</div>');
});

我在jsonResp下得到的xml是:

<?xml version="1.0" encoding="UTF-16"?>
<envio>
<version>1.0.0</version>
<anuncios>
<remitente>
<nodoRemitente>Nodo Remitente</nodoRemitente>
</remitente>
<anuncio>
<emisor>
<nodoEmisor>Nodo Emisor</nodoEmisor>
</emisor>
<metadatos>
<id>16249</id>
</metadatos>
<contenido>
<texto>
<p>
Notificación de prueba
</p>
<p>
Notificación de prueba
</p>
<p>
Notificación de prueba
</p>
</texto>
</contenido>
</anuncio>
</anuncios>
</envio>

在 Chrome 或 Fireforx 下,texto 返回

<texto>
<p>
Notificación de prueba
</p>
<p>
Notificación de prueba
</p>
<p>
Notificación de prueba
</p>
</texto>

这正是我想要的(texto 标签内的 HTML 代码),但在 Internet Explorer 中我得到的是 undefined

我已经看到了 textContent 属性,但这不是我想要的,因为它不是 HTML 代码。

有什么想法吗?

最佳答案

Internet Explorer 不为 XML 文档中的节点提供 outerHTML 属性(也不提供 innerHTML)。您可以使用 XMLSerializer (在 IE 9+ 中)解决这个问题:

var node = $(xml).find('texto')[0]; // get DOM node
// Try outerHTML. If not available, use XMLSerializer
var texto = node.outerHTML || new XMLSerializer().serializeToString(node);

您会注意到 texto 字符串可能会获得根节点的 xmlns 属性。但我认为这对您使用它的方式无关紧要。

关于javascript - IE 中未定义的 outerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45375945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com