简体   繁体   English

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

[英]XmlHTTPRequest: “XML Parsing Error: no element found”

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. 我尝试通过将其作为URL输入到浏览器来加载./leer/confesiones/ ,它就像一个魅力。 Fully valid XML. 完全有效的XML。 Using Firebug to inspect XHR under "Net" says so too, valid XML. 使用Firebug在“Net”下检查XHR也是如此,有效的XML。 The Console view is the one that gives me the error, like if it is a JavaScript error. Console视图是一个给我错误的视图,就像它是一个JavaScript错误一样。 But http.responseText contains the XML, in text, and xml is of type [object XMLDocument] . 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以正确解析它。

Do yourself a favor, and use a JS library that wraps all the ajax magic for you. 帮自己一个忙,并使用一个包含所有ajax魔法的JS库。 There's a lot of cross-browser issues and gotchas, and this may just be one of those things. 有很多跨浏览器的问题和陷阱,这可能只是其中之一。

I'd recommend jQuery, it's the easiest and quite powerful. 我推荐jQuery,它是最简单,最强大的。 So add this to the top of your html, inside the head tag: 所以将它添加到head标签内的html顶部:

<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 here for more info about jQuery and the $.get function. 在这里查看有关jQuery和$ .get函数的更多信息。 BTW- I see you're using a POST, but for retrieval of data (no updating or deleting) the convention is GET. 顺便说一句 - 我看到你正在使用POST,但是为了检索数据(没有更新或删除),约定是GET。

Additionally, consider changing your PHP so that it returns JSON formatted data instead of XML. 另外,请考虑更改PHP,以便它返回JSON格式的数据而不是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: 因此,与xml标记不同,不要做那个小小的舞蹈,只需准备一个包含所有数据的数组,然后执行以下操作:

echo json_encode($array); // voila
if (typeof window.ActiveXObject != 'undefined' ) {

I'd go for native XMLHttpRequest first. 我首先去寻找原生的XMLHttpRequest。 ActiveXObject should only be a fallback, as it may generate ugly ActiveX warnings. ActiveXObject应该只是一个后备,因为它可能会生成丑陋的ActiveX警告。

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

Accidental global. 意外全球。 Rememeber to use var . 记住使用var

    http.onreadystatechange = oncomplete;

onreadystatechange is called in more cases than just completion. 在更多情况下onreadystatechange而不仅仅是完成。 You should only call oncomplete when readystatechange fires and readyState===4 , otherwise you may be attempting to parse incomplete or missing XML. 您应该只在readystatechange触发和readyState===4时调用oncomplete ,否则您可能正在尝试解析不完整或缺少的XML。

    http.onload = oncomplete;

onload is not part of the XMLHttpRequest standard. onload不是XMLHttpRequest标准的一部分。 You should use onreadystatechange for both branches. 您应该为两个分支使用onreadystatechange

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响应与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回来的事实的副作用(因为浏览器不允许它)。

I don't know PHP, but I don't see where you're getting your closing tag for the <confession> element. 我不知道PHP,但是我看不到你在哪里获得<confession>元素的结束标记。 Call me confused, since you say the output is well-formed... 叫我困惑,因为你说输出结构良好......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM