似乎我的javascript没有拿起我的php发回一个xml文件。 php代码:
$domtree = new DOMDocument('1.0', 'UTF-8');
/* append it to the document created */
$xmlRoot = $domtree->appendChild($domtree->createElement("root"));
foreach (glob('./img/photos/*.*') as $filename) {
//echo $filename;
$xmlRoot->appendChild($domtree->createElement("image",$filename));
}
/* get the xml printed */
echo $domtree->saveXML();
以上代码的输出如下:
<?xml version="1.0" encoding="UTF-8"?>
<root><image>./img/photos/2012-02-26 17.02.12.jpg</image>
<image>./img/photos/2012-03-09 08.21.48.jpg</image>
<image>./img/photos/2012-07-21 14.09.39.jpg</image>
<image>./img/photos/2012-07-25 15.25.17.jpg</image>
<image>./img/photos/2012-08-04 17.54.38.jpg</image>
<image>./img/photos/2012-08-04 23.36.30.jpg</image>
<image>./img/photos/2012-08-06 06.08.43.jpg</image>
<image>./img/photos/2012-08-07 20.57.34.jpg</image>
<image>./img/photos/2012-08-09 20.40.11.jpg</image>
<image>./img/photos/2012-08-25 20.54.05.jpg</image>
<image>./img/photos/2012-09-07 11.19.50.jpg</image>
<image>./img/photos/2012-09-08 15.53.27.jpg</image>
<image>./img/photos/2013-01-30 19.19.16.jpg</image>
<image>./img/photos/2013-01-31 09.48.39.jpg</image></root>
用AJAX调用它,当我调用AJAXRequest.responseXML时,我得到null。
编辑:AJAX请求代码:
function requestImages()
{
request=new XMLHttpRequest();
request.open("GET", "getPhotos.php");
request.onreadystatechange=showPhotos;
request.send();
}
function showPhotos()
{
if ((request.readyState == 4)) {
doc=request.responseXML; // This returns null
}
}
答案 0 :(得分:1)
尝试在php中发送内容类型,以便AJAX知道这是一个xml并解析它(请记住,这必须在任何echo
之前完成):
header("Content-Type: text/xml");
这也可以直接在javascript(overrideMimeType()
)中强制执行,但最好在php中完成。
答案 1 :(得分:0)
如果您没有使用任何第三方库,请尝试使用此类代码段(根据您的要求进行修改)
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
请注意,它正在使用request.responseText,如果您要在标题中添加header("Content-type: text/xml");
内容类型,它肯定会获得返回的xml
<强>更新强>
要解析xml,您可以使用以下代码段:
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {} //use this for some processing at run time