У меня возникла проблема с загрузкой данных XML в javascript с помощью jQuery.
У меня есть xml здесь:
<config>
<device>
<node>1</node>
<name>Block</name>
<description>Block in saloon</description>
<area>Salon</area>
</device>
<device>
<node>2</node>
<name>Line</name>
<description>Lottr</description>
<area>Living room</area>
</device>
</config>
Я хотел бы найти имя устройства, где node = 2.
Вот код, который у меня есть:
$.ajax({
type: "GET",
url: "config2.xml",
dataType: "xml",
success: function(xml) {
var kurs = $(xml).find('name').text();
alert(kurs);
}
});
Что я должен положить в var kurs?
$(document).ready(function () {
$.ajax({
type: "GET",
url: "config2.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('device').each(function () {
var node = $(this).find('node');
if (node.text() == '2') {
name = $(this).find('name').text();
}
});
}
});
});
var myVal;
$(xml).find('node').each( //find the node and loop through them
function(){
var node = $(this);
if (node.text==="2") { //see if the node value is 2
myVal = node.siblings("name").text(); //find the sibling name element
return false; //exit the each loop
}
}
);
console.log(myVal);
Подобно этому вопросу: jQuery для получения совпадающих узлов в XML
Я думаю, что что-то вроде этого должно работать:
$.ajax({
type: "GET",
url: "config2.xml",
dataType: "xml",
success: function(xml) {
//this should get you the device node
var $kurs = $(xml).find('node:contains("2")').parent();
//this should get you the name from the device node
var name = $kurs.find('name');
}
});
kurs
и почему?