我正在关注newboston ajax教程,但遇到了错误。 我已经给出了错误的快照。我正在使用wamp服务器并在Chrome浏览器上运行它。Uncaught TypeError:无法读取属性'documentElement'的null message = xmlHttp.responseXML.documentElement.firstChild.data;
任何人都可以帮助我吗?
的index.html
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf=8" http-equiv="encoding">
<script type="text/javascript" src="food.js"></script>
</head>
<body onload="process()">
<h2>....Food Shop...</h2>
<input type="text" id="userinput" placeholder="enter the food u want" value="banana">
<div id="underinput" />
</body>
</html>
food.js
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObjects){
try{
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try{
xmlHttp= new XMLHttpRequest();
}catch(e)
{
xmlHttp=false;
}
}
if(!xmlHttp)
{
alert("cant create the object");
}
else{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
food=encodeURIComponent(document.getElementById("userinput").value);
xmlHttp.open("GET","foodstore.php?food=" + food,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 wrong...');
}
}
}
foodstore.php
<?php
error_reporting(E_ALL);
int_set('display_errors',true)
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF=8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray= array('banana','apple','mango');
if(in_array($food,$foodArray)){
echo 'we do have'.$food;
}
else if($food ==''){
echo 'enter the food';
}
else{
echo 'sorry we do not have'.$food;
}
echo '</response>';
?>
它告诉你'xmlHttp.responseXML'为空,所以你应该日志,看看服务器返回真的你 – adeneo
可以请告诉我如何登录 – Dharmesh
'的console.log(xmlHttp.responseXML) '和'console.log(typeof xmlHttp.responseXML)' – adeneo