2014-01-23 29 views
1

我试图用JS(Node和ajax(和jQuery库))替换我所有的PHP,但在将以下PHP脚本转换为ajax时遇到困难发动机。将PHP脚本转换为读取和打印XML数据的JavaScript脚本

<?php 
    $xmlDoc=new DOMDocument(); 
    $xmlDoc->load("Administration/data/people.xml"); 

    $xx=$xmlDoc->getElementsByTagName('person'); 

    $hintt=""; 
    for($ii=0; $ii<($xx->length); $ii++) 
     { 
     $yy=$xx->item($ii)->getElementsByTagName('id'); 
     $zz=$xx->item($ii)->getElementsByTagName('fullName'); 
     if ($yy->item(0)->nodeType==1) 
     { 

      echo "<button type='button' class='mybutton' name='users'>" . 
      $zz->item(0)->childNodes->item(0)->nodeValue . "</button>"; 

     } 
     } 

    ?> 

这里是我的ajax尝试:

 <div id="loadMe"> 
      <h1>Reading..</h1> 
     </div> 

     <script> 
       $.ajax({ 
        type: "GET", 
        url: "Administration/data/people.xml", 
        dataType: "xml", 
        success: function(xml) { 
         $(xml).find('person').each(function(){ 
          var fullName = $(this).attr('fullName'); 
          $("<button type=button class=mybutton value='+fullName+'></button>").html("<h3>'+fullName+'</h3>").appendTo('#loadMe'); 
         }); 
        } 
       }); 
     </script> 

对我来说,它看起来非常相似,但JS是行不通的。任何人看到不一致或可以告诉我为什么我的XML元素不附加到指定的div标签?提前感谢球员和球员!编辑(1/24/14 1:24 AM): 我认为提供我的XML会有帮助,也许我引用的数据是错误的?

<people> 
    <person> 
    <id>10</id> 
    <fullName>Philadelphia Collins</fullName> 
    <firstName>Philadelphia</firstName> 
    <lastName>Collins</lastName> 
    <age>62</age> 
    <hometown>Sunnyvale</hometown> 
    <job>Restraunt Owner</job> 
    </person> 
<people> 
+0

你应该做'.done()'和'.fail()'而不是'成功:' –

+2

'$('

+0

我用过,但这不是问题的原因@Blazemonger你是否看到任何逻辑错误? – Jim22150

回答

0

我已经成立了一个test page,你可以尝试和玩,如果在任何时候你需要做更多的探索。所以解决方案就来了。

首先,我试着做一个AJAX请求,由于XML无效,它总是返回失败。如果我只是试图访问XML,它表示它无效并且无法显示。问题是关闭<people>标签丢失/。它应该是</people>'. So that fixed the AJAX request failing. The next part was parsing the XML response. I did this by using the .children()method in jQuery and then getting the text of the element with .text()`。它结束了看起来像这样:

var fullName = $(this).children('fullName').text(); 
与所有

所以和别的我可能已经错过了,但可在测试页,我希望你能解决您的问题,并获得成功的AJAX请求去。如果我错过了任何东西或者我不清楚,请告诉我,我会尽量多解释一下。

顺便说一下,在Chrome DevTools中使用console.log();并使用断点来自己访问数据总是可以帮助我了解我正在处理的内容,这样我就知道如何从请求中获取我想要的数据。

祝你好运!

+0

我的答案是否适合你? –