我正在观看有关 Ajax 培训的 New Boston 教程,我编写了与类(class)导师相同的代码。但是代码在我的电脑上不起作用。
在谷歌浏览器中
Uncaught TypeError: Cannot read property 'documentElement' of null
message = xmlHttp.responseXML.documentElement.firstChild.data;
在火狐中
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>
书名.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>';
?>
书名.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!');
}
}
}
最佳答案
您的 PHP 代码无效,因为:
- 你错过了
;
在echo 'Sorry we don\'t have user "'. $name . '" ';
- 结束括号
)
在if(in_array($name, $nameArray))
中丢失 -
>
在document.getElementById("underInput").innerHTML = '<span style="color: blue">' + message + '</span>';
中丢失
关于javascript - Ajax,无法读取 null 的属性 'documentElement',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29673081/