使用jQuery获取simpleXMLElement

时间:2010-02-19 20:46:53

标签: php jquery xml simplexml

如何使用jquery从php文件中检索simpleXMLElement变量的内容?

1 个答案:

答案 0 :(得分:0)

发送SimpleXMLElement::asXML()

的返回值

自包含的例子:

<?php
if ( isset($_GET['foo']) ) {
  $foo = new SimpleXMLElement('<foo />');
  $foo->bar->baz[] = date('Y-m-d H:i:s');
  $foo->bar->baz[] = rand(1,100)." la la la";
  header('Content-type: application/xml; charset=utf-8');
  echo $foo->asXML();
  die;
}
?><html>
  <head>
    <title>...</title>
    <script type="text/javascript" src="jquery/jquery-1.3.2.min.js"></script>
    <script type="text/javascript">
      function foo() {
        $.ajax({
          type: "GET",
          url: "?",
          data: { "foo":1 },
          dataType: "xml",
          success: function(xml) {
             $(xml).find("baz").each(function(){
               $("#div1").append($(this));
               $("#div1").append("<br />");
             })
          },
          error: function() {
            alert("that didn't work");
          }
        });
      }
    </script>
  </head>
  <body>
    <button onclick="foo()">click</button>
    <div id="div1">...</div>
  </body>
</html>