我该如何将这个XML对象放入一个javascript字典?

时间:2012-05-09 11:08:41

标签: jquery xml jquery-selectors

我应该如何将这个XML对象放入javascript字典中?

来自get_objectives.php的

XMLcoming:

<container>
  <objective>
    <id>1</id>
    <type>thing</type>
    <name>banana</name>
    <date_added>2012-05-08 21:13:01</date_added>
    <released>2012-05-08 22:47:27</released>
  </objective>
  <objective>
    <id>2</id>
    <type>thing</type>
    <name>hammock</name>
    <date_added>2012-05-08 21:13:01</date_added>
    <released>2012-05-08 22:47:27</released>
  </objective>
</container>

无效的javascript,我正试图修复:

function updateObjectives(){
  $.post('scripts/get_objectives.php', {}, function(xml){
    $(xml).find("objective").each(function(i){
      objectives[i] = {}
      objectives[i]['id'] = $('id', xml).text()
      console.log("objectives["+i+"].id = "+objectives[i].id)
    })
  })
}

根据下面的控制台输出,似乎我正在尝试的$('id', xml).text()调用不会停留在处理find(“objective”)的函数内。每次调用:

objectives[0].id = 12
objectives[1].id = 12

1 个答案:

答案 0 :(得分:0)

objectives[i]['id'] = $('id', this).text()可以解决问题!

我的问题是教程中$()的暧昧语法; $(query, context)。而不是寻找正在寻找的('this > id', xml)这个孩子名为&#39; id&#39;在完整的&#39; xml&#39;文件,(我已经找到了这个&#39;!)所以$('id', this)有效,因为它正在寻找&#39; id&#39;在里面&#39;这个&#39; (其中&#39;这是标签)我希望这有助于某人!