我正在使用jquery和javascript处理xml。我使用 ajax 导入 xml,然后我想操作它,appendChild 是 IE8 中的一个问题。
这是Javascript:
// How i get xml
$.ajax({
url: production_get,
dataType: "xml",
success: function(data) {
input_xml=data;
}
});
// how i try to append a new node to
new_user_node = document.createElement('user');
new_user_node.setAttribute('id',new_user_id);
new_user_node.setAttribute('label',new_user_label);
response=$(input_xml)[0].getElementsByTagName("response")[0];
response.appendChild(new_user_node); // <- type mismatch
XML 标记
<response>
<user id="123" label="John" />
</response>
这适用于所有浏览器,但报告:类型不匹配的 IE 除外。我不得不说它即使在IE8中也可以工作,但是控制台报告了错误,而在IE7中出现了错误弹出窗口
当你在
jQuery中包装xml时,它会将xml视为html。这允许遍历获取属性和文本,但不足以修改 xml。
要创建要附加到的 XML 文档,您需要使用$.parseXML()
/* First create xml doc*/
var xmlDoc=$.parseXML(input_xml);
/*Create jQuery object of xml doc*/
var $xml= $( xmlDoc);
/*Now append*/
$xml.append( new_user_node);
http://api.jquery.com/jQuery.parseXML/
API 中的更多示例