Javascript XmlHTTPRequest:“XML 解析错误:未找到元素”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2212068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:15:18  来源:igfitidea点击:

XmlHTTPRequest: "XML Parsing Error: no element found"

phpjavascriptmysqlxmlajax

提问by Joel A. Villarreal Bertoldi

So I'm using PHP+MySQL to deliver database contents in XML to a JavaScript.

所以我使用 PHP+MySQL 将 XML 中的数据库内容传递给 JavaScript。


$xml = "<?xml version='1.0' encoding='utf-8'?><confessions><pending>";
$pending = $m->MySqlHandler->Query("SELECT id, gender, age, confession, date_posted FROM confessions WHERE publish = 0");
foreach ($pending->Rows as $pr)
{
   list($id, $gender, $age, $confession, $dateposted) = array(
     $pr->Columns["id"]->Value,
     $pr->Columns["gender"]->Value,
     $pr->Columns["age"]->Value,
     $pr->Columns["confession"]->Value,
     $pr->Columns["date_posted"]->Value
   );
   $xml .= "<confession id='$id' gender='$gender' age='$age' dateposted='$dateposted'>$confession</confession>";
}

$xml .= "</pending>"; $xml .= "<active>";

$active = $m->MySqlHandler->Query( "SELECT DISTINCT confessions.*, (SELECT COUNT(*) FROM comments WHERE confession_id = confessions.id) AS comments, (SELECT COUNT(*) FROM sentences WHERE confession_id = confessions.id) AS sentences FROM confessions WHERE confessions.publish = 1" );

foreach ($active->Rows as $ar) { list($id, $gender, $age, $confession, $dateposted, $absolutions) = array( $ar->Columns["id"]->Value, $ar->Columns["gender"]->Value, $ar->Columns["age"]->Value, $ar->Columns["confession"]->Value, $ar->Columns["dateposted"]->Value, $ar->Columns["absolutions"]->Value ); $sql_template = "SELECT COUNT(*) FROM sentences WHERE confession_id = $id AND degree = '%s'"; $sentence_data = array( "t" => mysql_result(mysql_query(sprintf($sql_template, "t")), 0, 0), "c" => mysql_result(mysql_query(sprintf($sql_template, "c")), 0, 0), "p" => mysql_result(mysql_query(sprintf($sql_template, "p")), 0, 0), "l" => mysql_result(mysql_query(sprintf($sql_template, "l")), 0, 0) ); $xml .= "<confession absolutions='$absolutions' t='{$sentence_data['t']}' " . "c='{$sentence_data['c']}' p='{$sentence_data['p']}' " . "l='{$sentence_data['l']}' id='$id' gender='$gender' " . "age='$age'>$confession</confession>"; }

$xml .= ""; header("Content-Type: application/xml"); echo $xml;

So, from there, you get a result such as...

所以,从那里,你会得到一个结果,比如......


<?xml version='1.0' encoding='utf-8'?>
<confessions>
  <pending>
    <confession id="1" gender="m" age="20" dateposted="2010-02-06 05:22:57">
      Confesando.
    </confession>
  </pending>
  <active>
    <confession absolutions="0" t="0" c="0" p="0" l="0" id="2" gender="m" age="18">
      Confesion.
    </confession>
  </active>
</confessions>

I load the XML with JavaScript by using:

我使用 JavaScript 加载 XML:


function sendData(params, to, oncomplete)
{
    if (typeof oncomplete == 'undefined')
    {
        oncomplete = function() {};
    }
    if (typeof window.ActiveXObject != 'undefined' ) {
        http = new ActiveXObject("Microsoft.XMLHTTP");
        http.onreadystatechange = oncomplete;
    } else {
        http = new XMLHttpRequest();
        http.onload = oncomplete;
    }
    http.open("POST", to, false);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-Length", params.length);
    http.setRequestHeader("Connection", "close");
    http.send(params);
}

...which is called like this:

...这是这样调用的:


// Load approval-pending data //
sendData("", "./leer/confesiones/" + sId, function()
{
   var xml = http.responseXML;
   var pending = xml.getElementsByTagName("pending").getElementsByTagName("confession");
(...)

I'll stop right here. Because when I attempt to parse the XML I get the following error at Firebug:

我就停在这里。因为当我尝试解析 XML 时,我在 Firebug 中收到以下错误:


XML Parsing Error: no element found Location: moz-nullprincipal:{7e9eab45-2f73-476d-9bdb-2370d1534f29} Line Number 1, Column 1:
^

I tried loading ./leer/confesiones/by inputting it as an URL into the browser and it works like a charm. Fully valid XML. Using Firebug to inspect XHR under "Net" says so too, valid XML. The Console view is the one that gives me the error, like if it is a JavaScript error. But http.responseTextcontains the XML, in text, and xmlis of type [object XMLDocument].

我尝试./leer/confesiones/通过将其作为 URL 输入到浏览器中来加载,它的工作原理非常棒。完全有效的 XML。使用 Firebug 在“Net”下检查 XHR 也是如此,有效的 XML。控制台视图是给我错误的视图,就像是 JavaScript 错误一样。但http.responseText包含文本形式的 XML,并且xml类型为[object XMLDocument]

So... what am I missing?

所以……我错过了什么?

SOLVED: modified PHP to output JSON and JavaScript to parse it properly.

已解决:修改 PHP 以输出 JSON 和 JavaScript 以正确解析它。

回答by adamJLev

Do yourself a favor, and use a JS library that wraps all the ajax magic for you. There's a lot of cross-browser issues and gotchas, and this may just be one of those things.

帮自己一个忙,使用一个 JS 库,它为您包装了所有的 ajax 魔法。有很多跨浏览器的问题和陷阱,这可能只是其中之一。

I'd recommend jQuery, it's the easiest and quite powerful. So add this to the top of your html, inside the head tag:

我推荐 jQuery,它是最简单且功能强大的。因此,将此添加到您的 html 顶部的 head 标记内:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> 

And then in your JS do something like this:

然后在你的 JS 中做这样的事情:

 $.get('/leer/confesiones/', function(data) {
     console.log(data);
 });

That should get you started. Look herefor more info about jQuery and the $.get function. BTW- I see you're using a POST, but for retrieval of data (no updating or deleting) the convention is GET.

这应该让你开始。在此处查看有关 jQuery 和 $.get 函数的更多信息。顺便说一句-我看到您正在使用 POST,但是对于数据检索(不更新或删除),约定是 GET。

Additionally, consider changing your PHP so that it returns JSON formatted data instead of XML. So instead of doing that little dance you have to do with the xml markup, just get an array ready with all the data, and do this:

此外,请考虑更改您的 PHP,使其返回 JSON 格式的数据而不是 XML。因此,您不必使用 xml 标记做那种小舞,只需准备一个包含所有数据的数组,然后执行以下操作:

echo json_encode($array); // voila

回答by bobince

if (typeof window.ActiveXObject != 'undefined' ) {

I'd go for native XMLHttpRequest first. ActiveXObject should only be a fallback, as it may generate ugly ActiveX warnings.

我会首先使用本机 XMLHttpRequest。ActiveXObject 应该只是一个后备,因为它可能会生成丑陋的 ActiveX 警告。

    http = new ActiveXObject("Microsoft.XMLHTTP");

Accidental global. Rememeber to use var.

意外全球。记得使用var.

    http.onreadystatechange = oncomplete;

onreadystatechangeis called in more cases than just completion. You should only call oncompletewhen readystatechangefires and readyState===4, otherwise you may be attempting to parse incomplete or missing XML.

onreadystatechange在更多情况下被调用,而不仅仅是完成。您应该只oncompletereadystatechange触发 and时调用readyState===4,否则您可能会尝试解析不完整或丢失的 XML。

    http.onload = oncomplete;

onloadis not part of the XMLHttpRequest standard. You should use onreadystatechangefor both branches.

onload不是 XMLHttpRequest 标准的一部分。您应该onreadystatechange用于两个分支。

回答by Tom Lianza

I'm a bit surprised if JQuery solved this particular issue... at least, you can generate the same errors with that: XMLHttpRequest xml response woes with jQuery 1.4.1, how to force the request response to be processed as plain text?

如果 JQuery 解决了这个特定问题,我有点惊讶……至少,您可以生成相同的错误: XMLHttpRequest xml response woes with jQuery 1.4.1,如何强制将请求响应作为纯文本处理?

In my case, at least, this was all due to the fact that I was making a cross-domain request, and the XML error about it being "unparsable" was just a side effect of the fact that no XML came back (because the browser didn't allow it).

至少在我的情况下,这完全是因为我正在发出跨域请求,而关于它“无法解析”的 XML 错误只是没有返回 XML 的副作用(因为浏览器不允许)。

回答by BobS

I don't know PHP, but I don't see where you're getting your closing tag for the <confession>element. Call me confused, since you say the output is well-formed...

我不懂 PHP,但我不知道您从何处获取<confession>元素的结束标记。叫我困惑,因为你说输出格式正确......