为什么不能在post()调用中使用dataType =“xml”?

时间:2013-07-19 04:27:18

标签: php jquery

我有一个 post()调用,它读取了一个xml文件,因为这是一个lproper xml文件,我觉得应该可以,我应该创建dataType =“xml”。但这打破了电话。如果我使dataType =“text”,它工作正常。有没有人看到这个问题?

$.post('loadPage.php', { siteName : siteName},function(xml) {
Status2$.html(xml);
var bdystyle = $(xml).find("bodyStyle")[0].textContent;
var canvasstyle = $(xml).find("canvasStyle")[0].textContent;
},
"text"); 

php是:

<?php
    $siteName       = $_POST['siteName'];
    $fileName = "{$siteName}_sav.xml";
    $fileSize = filesize($fileName);
    $filePath =  $_SERVER['DOCUMENT_ROOT'] . "/" . $fileName;
    $site_fp = fopen( $filePath, 'r');
    $xml = fread($site_fp, $fileSize);
    echo $xml;
?>

xml文件是:

<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
   <bodyStyle>background-image: none; background-color: rgb(255, 254, 253); cursor: auto;</bodyStyle>
   <canvasStyle>background-image: none; background-color: rgb(255, 26, 0);</canvasStyle>
   <canvasData>This is where the canvas html would go.</canvasData>
</root>

2 个答案:

答案 0 :(得分:0)

我相信你的php代码需要发回适当的Content-Type标头,以便jQuery(或某些浏览器?)正确解释它。

header('Content-Type: text/xml'); // or 'application/xml'

答案 1 :(得分:0)

我不知道为什么我不能将dataType指定为“xml”但事实证明我没有必要让jQuery将下载的文件视为XML并为我提取单个组件,这是这里的目标。如果使用ajax加载的文件是:

<?xml version="1.0" encoding="ISO-8859-1"?>
<root>  
   <bodyStyle>body style will go here;</bodyStyle>
   <canvasStyle>canvas style will go here</canvasStyle>
   <canvasData>canvas data will go here</canvasData>
</root>

然后我需要提取文件的三个组件:

$.post('loadPage.php', { siteName : siteName},function(xml) {
    var bodyStyle = $(xml).find("bodyStyle")[0].textContent;
    var canvasStyle = $(xml).find("canvasStyle")[0].textContent;
    var canvasData = $(xml).find("canvasData")[0].textContent;
});

其中loadPage.php是

<?php
    $siteName = $_POST['siteName'];
    $fileName = "{$siteName}.xml";
    $fileSize = filesize($fileName);
    $filePath =  $_SERVER['DOCUMENT_ROOT'] . "/" . $fileName;
    $site_fp = fopen( $filePath, 'r');
    $data = fread($site_fp, $fileSize);
    echo $data;
?>