【问题标题】:PHP load as XML in JQueryPHP 在 JQuery 中加载为 XML
【发布时间】:2012-08-19 23:45:30
【问题描述】:

我正在尝试加载 XML 以填充搜索框。我的代码在静态 xml 文件中运行良好,但我需要加载 PHP 文件以根据数据库中的数据生成动态 XML 文件。

我知道 PHP 文件在浏览器中加载时会生成 XML,并且页面源会显示正确的节点等,但是当我在 JavaScript 中引用 .php 文件时,它无法加载或显示错误...使用 .xml 文件(它是 php 输出源的副本)可以正常加载。

我希望有人检查我是否正确编码了 XML 或在我的 JavaScript 中遗漏了某些内容......我们将不胜感激。

JS

var myArr = [];
$.ajax({            
     url: "people.php", // change to full path of file on server
     type: "GET",
     dataType: "xml",
     success: parseXml,
     complete: setupAC,
     failure: function(data) {
       alert("XML File could not be found");
     }
});

function parseXml(xml){
     $(xml).find("person").each(function(){     
        var thisItem = $(this).find('name').text();
        myArr.push(thisItem);
        alert(thisItem);
     });    
}

PHP

<?php

    include '../../inc_global/connect.php';

    $query = 'SELECT * FROM candidates';  

    $result = mysql_query($query, $link);

    $xmlOutput = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    $xmlOutput .= "<people>\n";

    while ($line = mysql_fetch_assoc($result)) {

   $xmlOutput .= "<person>\n"; 
   $xmlOutput .= "<name>" . $line['name'] . "</name>\n"; 
   $xmlOutput .= "</person>\n";

}

$xmlOutput .= "</people>\n";

echo $xmlOutput;

mysql_close($link);

?>

【问题讨论】:

  • 尝试删除 dataType: "xml", 属性
  • 3nigma - 立即生效!谢谢你,但我不知道为什么?这与我缺少的标题(“Content-Type:text/xml”)声明有关吗?

标签: php jquery xml xml-parsing


【解决方案1】:

您能否确保函数 parseXml(xml) 在 ajax 调用成功时调用它时不需要任何参数。请注意,我没有尝试过代码,但这里只是猜测。

【讨论】:

    【解决方案2】:

    检查 php 中发生的情况,将浏览器指向 people.php

    无论如何我建议你:

    为 PDO 删除 mysql_

    因为mysql_ 的功能很差,会阻止遇到小鸡,而PDO 有帮助;

    对原始 XML 使用 SimpleXML

    SimpleXML 帮助您构建代码,而不会因为链接字符串而烦恼。

    为您的文档提供正确的 HTTP 标头

    您正在生成一个 XML 文档,让浏览器意识到这一点:

    header ("Content-Type:text/xml");  
    echo $xmlOutput;
    

    【讨论】:

      【解决方案3】:

      尽量在输出信息前加上标题:

      ....
      header ("Content-Type:text/xml");  
      echo $xmlOutput;
      ....
      

      完整代码:

      <?php
      
          include '../../inc_global/connect.php';
      
          $query = 'SELECT * FROM candidates';  
      
          $result = mysql_query($query, $link);
      
          $xmlOutput = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
          $xmlOutput .= "<people>\n";
      
          while ($line = mysql_fetch_assoc($result)) {
      
         $xmlOutput .= "<person>\n"; 
         $xmlOutput .= "<name>" . $line['name'] . "</name>\n"; 
         $xmlOutput .= "</person>\n";
      
      }
      
      $xmlOutput .= "</people>\n";
      
      header ("Content-Type:text/xml");  //<----------- xml header here
      echo $xmlOutput;
      
      mysql_close($link);
      
      ?>
      

      【讨论】:

        猜你喜欢
        • 2012-06-24
        • 1970-01-01
        • 1970-01-01
        • 2013-01-05
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 1970-01-01
        • 2011-05-30
        相关资源
        最近更新 更多