我通过$ .ajax()get获得以下类似XML的字符串。因为它无效,所以我不能使用dataType:'xml'或用$ .parseXML()解析。尽管使用xml作为字符串,并使用jQuery来遍历它似乎工作正常。我可以使用find()方法读取属性,但我似乎无法设置值。 (我只能得到XML,它是由另一个部门提供的,我无法对其进行更改)。使用jQuery设置XML字符串中的值
TLDR:需要操纵xml字符串。添加用户,密码和类型值,以便将其发送回服务器。
var xml = '<attrs xmlns="http://www.blah.com/abc/wxyz"><attr name="user" type="string"/><attr name="password" type="string"/><attr name="type" type="string" possibilities="typeOne,typeTwo,typeThree,typeFour">typeOne</attr></attrs>';
/*
<attrs xmlns="http://www.blah.com/abc/wxyz">
<attr name="user" type="string"/>
<attr name="password" type="string"/>
<attr name="type" type="string" possibilities="typeOne,typeTwo,typeThree,typeFour">typeOne</attr>
</attrs>
*/
// The following works fine. I get the possibilites, split them, and add them to a form:
$.each($(xml).find('attr[possibilities]').attr('possibilities').split(','), function(index,value){
options += '<option value="'+value+'">'+value+'</option>';
});
// I have tried the text(), prop(), and attr() methods. From what I've read you are supposed to use prop() instead of attr for setting values, but I tried attr anyway.
$(xml).find('attr[name=user]').attr('textContent', 'TEST');
$(xml).find('attr[name=user]').text('TEST');
$(xml).find('attr[name=user]').prop('textContent', 'TEST');
// After attempting attr, text, and prop, the textContent property shows nothing (not undefined):
console.log('textContent ' + $(xml).find('attr[name=user]').prop('textContent'));
我在这方面比较新,所以有可能我的选择器是错的。任何帮助表示赞赏。提前致谢。
哇,我是新来的,但我不能相信我没有注意到这一点。这样可行。感谢您及时的回复。 – 2012-03-29 20:46:27
非常感谢.....最上线拯救了我的一天..... – 2014-12-03 06:38:59