【发布时间】:2015-08-12 16:40:15
【问题描述】:
我正在使用 ajax 和 php&mysql 检查用户名是否存在于数据库中。浏览器在弹出窗口中抛出以下错误:
读取响应时出错:无效的 XML
我的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;
}
}
?>
【问题讨论】:
-
ajax请求的响应是什么?您也可以使用此代码进行 SQL 注入;不要将用户输入直接传递给您的查询。
-
你是对的,我没有使用 mysql_escape_string,因为我只是在测试 ajax。如果能解决上面的错误就更好了。
-
你忽略了我评论的第一部分? ajax请求的响应是什么?
-
如果数据库中已经存在用户名,则响应为“用户名退出”,否则为“可用”
-
您是否在开发者控制台中查看请求? commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art034
标签: javascript php ajax xml ajaxform