我正在观看关于Ajax培训的新波士顿教程,我编写了与课程导师相同的代码。但是代码在我的电脑中不起作用。
在Google Chrome中
Uncaught TypeError: Cannot read property 'documentElement' of null
message = xmlHttp.responseXML.documentElement.firstChild.data;
在Firefox中
not-well formed bookname.php:5:8
echo '<response>';
的index.html
<body onload="process()">
<h1>Users information</h1>
Enter user_name you would want to know about:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
bookname.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$name = $_GET['userName'];
$nameArray = array('Mehrshad', 'Alex', 'Tom', 'Aydin');
if(in_array($name, $nameArray)
{
echo 'I do know '. $name . '!';
}
else if($name == '')
{
echo 'Enter a name you want to know about';
}
else
{
echo 'Sorry we don\'t have user "'. $name . '" '
}
echo '</response>';
?>
bookname.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlHttp = false;
}
}
else
{
try{
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert('can\'t create that object hoss!')
}
else
{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
username = encodeURIComponent(document.getElementById('userInput').value);
xmlHttp.open("GET", "bookname.php?userName=" + username, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
message = xmlHttp.responseXML.documentElement.firstChild.data;
document.getElementById("underInput").innerHTML =
'<span style="color: blue"' + message + '</span>';
setTimeout('process()', 1000);
}
else
{
alert('Something went wrong!');
}
}
}
答案 0 :(得分:2)
你的php代码无效,因为:
;
echo 'Sorry we don\'t have user "'. $name . '" ';
)
if(in_array($name, $nameArray))
>
中缺少document.getElementById("underInput").innerHTML = '<span style="color: blue">' + message + '</span>';
醇>
答案 1 :(得分:1)
我也正在运行相同的代码,但是显示了与上述相同的错误。请提出解决方案,因为我仍然没有犯上述错误,但仍然显示Uncaught TypeError:无法读取XMLHttpRequest.handleServerResponse的null属性'documentElement'。
答案 2 :(得分:0)
http_request.overrideMimeType('application / xml');当IAm在IE和chrome迁移之间进行修复时,为我工作了