读取响应时出错:无效的XML错误

时间:2015-05-29 17:45:29

标签: javascript php ajax xml ajaxform

我正在使用带有php&的ajax检查数据库中是否存在用户名MySQL的。浏览器在弹出窗口中抛出以下错误:

  

读取响应时出错:XML无效

enter image description here

我的HanleServerResponse()功能:

function handleServerResponse() {
    // retrieve the server's response packaged as an XML DOM object
    var xmlResponse = xmlHttp.responseXML;

    // catching potential errors with IE and Opera
    if (!xmlResponse || !xmlResponse.documentElement)
        throw("Invalid XML structure:\n" + xmlHttp.responseText);

    // catching potential errors with Firefox
    var rootNodeName = xmlResponse.documentElement.nodeName;
    if (rootNodeName == "parsererror")
        throw("Invalid XML structure:\n" + xmlHttp.responseText);

    // getting the root element (the document element)
    xmlRoot = xmlResponse.documentElement;

    // testing that we received the XML document we expect
    if (rootNodeName != "response" || !xmlRoot.firstChild)
        throw("Invalid XML structure:\n" + xmlHttp.responseText);

    // the value we need to display is the child of the root <response> element
    responseText = xmlRoot.firstChild.data;

    // display the user message
    myDiv = document.getElementById("myDivElement");
    myDiv.innerHTML = "Server says the answer is: " + responseText;
}

我的ajax.php文件:

<?php
    header('Content-Type: text/xml');
    include ("./inc/connect.inc.php");

    $username = $_GET['username'];
    $query = mysql_query("SELECT fname FROM users WHERE fname='$username';");
    while($row = mysql_fetch_assoc($query)) {
        $name = $row['fname'];
        if ($name == $username) {   
            $dom = new DOMDocument();
            $response = $dom->createElement('response');
            $dom->appendChild($response);
            $text = $dom->createTextNode('username exits');
            $response->appendChild($text);
            $xml_string=$dom->saveXML();
            echo $xml_string;
        } else {
            $dom = new DOMDocument();
            $response = $dom->createElement('response');
            $dom->appendChild($response);
            $text = $dom->createTextNode('username available');
            $response->appendChild($text);
            $xml_string=$dom->saveXML();
            echo $xml_string;
        }
    }
?>

1 个答案:

答案 0 :(得分:0)

这不是一个答案,但它可能会给其他人一个解决问题的线索。

OP发布的代码片段似乎按预期工作。 PHP生成一个xml响应,Javascript能够提取值。复制报告错误的唯一方法是通过修改xml,例如添加前导空格。 OP可能会尝试添加&#34; ob_end_clean();&#34;声明到PHP部分以清除任何无关输出的响应缓冲区(最佳猜测)。并且查看完整的XMLHttpRequest将有助于故障排除。

OP代码测试数据库中的名称并返回以下响应之一:

匹配

<?xml version="1.0"?>
<response>username exits</response>

不匹配:

<?xml version="1.0"?>
<response>username available</response>

通过将它们提供给DOMParse以生成xml文档来测试这两个响应:

  var parser = new DOMParser();
  var xmlResponse = parser.parseFromString( strXml,"text/xml");

未发现任何错误。接下来,将xml提供给OP的函数 handleServerResponse()。它在两种情况下都返回了正确的值。