2014-02-19 58 views
0

我有一個問題,加載XML數據到JavaScript使用jQuery。Javascript XML加載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> 

我想找到設備名稱,其中節點是= 2

這裏是我的代碼:

 $.ajax({ 
     type: "GET", 
     url: "config2.xml", 
     dataType: "xml", 
     success: function(xml) { 
      var kurs = $(xml).find('name').text(); 
      alert(kurs); 
     } 
    }); 

應該是什麼我把var kurs?

+0

我不明白你的問題。你想把什麼放在'kurs'裏面,爲什麼? –

+0

問題到底是什麼?文件是否被加載? – Lix

回答

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

     }); 
    } 
    }); 

});

0
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's value is 2 
      myVal = node.siblings("name").text(); //find the sibling name element 
      return false; //exit the each loop 
     } 
    } 
); 
console.log(myVal); 
0

這個問題類似:jQuery to get matching nodes in 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'); 
    } 
});