从jquery ajax的XML格式化响应中读取值

时间:2021-09-05 07:29:04

I am sending a request to a URL using $.get(). The response text returns with the following XML:

我正在使用$ .get()向URL发送请求。响应文本返回以下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>

I need to get the text inside the <myValue> and </myValue> tag:

我需要在 和 标记内获取文本:

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

I have tried the following code inside $.get() function:

我在$ .get()函数中尝试了以下代码:

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

but there is no value in variable x.

但变量x中没有值。

2 个解决方案

#1


2  

Just wrap the xml with $ (jQuery) function, then you can use .find to find the node. Something like $(xml).find('myValue').html()

只需用$(jQuery)函数包装xml,然后就可以使用.find来查找节点。像$(xml).find('myValue')。html()

Demo (In this demo I'm not using ajax but the principle is the same):

演示(在这个演示中,我不使用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>

#2


1  

Try this:

$.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())
}

Documentation: https://api.jquery.com/jQuery.parseXML/

#1


2  

Just wrap the xml with $ (jQuery) function, then you can use .find to find the node. Something like $(xml).find('myValue').html()

只需用$(jQuery)函数包装xml,然后就可以使用.find来查找节点。像$(xml).find('myValue')。html()

Demo (In this demo I'm not using ajax but the principle is the same):

演示(在这个演示中,我不使用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>

#2


1  

Try this:

$.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())
}

Documentation: https://api.jquery.com/jQuery.parseXML/