2016-12-01 101 views
3

我使用$.get()向URL发送请求。响应文本返回与下面的XML:从jquery ajax的XML格式化响应读取值

<?xml version="1.0" encoding="UTF-8" ?> 
<myNode> 
    <cmd>Requested Item</cmd> 
    <myValue>this is the text i need to get with jquery</myValue> 
    <res>OK</res> 
</myNode> 

我需要得到<myValue></myValue>标签上的文字:

<myValue>this is the text i need to get with jquery</myValue> 

我曾尝试在$获得()函数下面的代码:

$.get(url,function(xml){ 
    var x, i, attnode, xmlDoc, txt; 
    xmlDoc = xml.responseXML; 
    x = xmlDoc.getElementsByTagName('data'); 
} 

但是在变量x中没有值。

回答

2

只是包装的XML与$(jQuery的)功能,那么你可以使用.find找到节点。像$(xml).find('myValue').html()

演示的东西(在本演示中,我没有使用AJAX,但原理是一样的):

var xml = '<?xml version="1.0" encoding="UTF-8" ?>' + 
 
    '<myNode>' + 
 
    '<cmd>Requested Item</cmd>' + 
 
    '<myValue>this is the text i need to get with jquery</myValue>' + 
 
    '<res>OK</res>' + 
 
    '</myNode>'; 
 

 
var x = $(xml).find('myValue').html(); 
 
console.log(x);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

精彩的解决方案。谢谢。 –

+0

我的荣幸:)祝你好运.. –

1

试试这个:

$.get(url,function(xml){ 
    var x, i, attnode, xmlDoc, txt; 
    xmlDoc = $.parseXML(xml.responseXML); 
    var $xml = $(xmlDoc); 
    var myValue= $xml.find("myValue"); 
    console.log(myValue.text()) 
} 

文档:https://api.jquery.com/jQuery.parseXML/

+0

是它也工作。我注意到,我没有搜索结果作为$(xml)...再次感谢 –