将PHP脚本转换为读取和打印XML数据的JavaScript脚本

时间:2014-01-23 21:49:27

标签: javascript php jquery ajax xml

我试图用JS(Node和ajax(和jQuery库))替换我的所有PHP,但是将以下PHP脚本转换为ajax引擎时遇到了麻烦。

    <?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标签?非常感谢你们和男士们!

编辑(2014年1月24日上午1:24): 我认为提供我的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>

1 个答案:

答案 0 :(得分: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();并使用断点来访问数据我总能帮助我了解我正在使用的内容,这样我就知道如何获取我想要的数据请求。

祝你好运!