【发布时间】: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