我正在通过遵循newboston的教程学习如何使用AJAX。我一直收到xmlHttpRequest
状态为0而不是200.我已查询状态0是什么,并且表明我的请求未初始化。我一直在研究我的文件,但我无法弄清楚它为什么会这样做。
我相信我把它缩小到xmlHttp.open
不正确"链接"?到我的foodstore.php文件,或者foodstore.php
文件中有错误写入的内容。
我的文件都存储在htdocs文件夹中,Apache Web Server在XAMMP 1.8.3-4上本地运行。
的index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The Chuff Bucket</h3>
Enter the food you would like to order:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
</html>
foodstore.js
var xmlHttp = createXmlHttpRequestObject();
//creates connection object
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("cant create that object boss!");
else
return xmlHttp;
}
//processes object
function process(){
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4){
alert('process run!');
var food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET", "foodstore.php?food="+food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
alert('process NOT run!');
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4){
//check if communication session is OK. no errors
alert('xmlHttp status: ' + xmlHttp.status);
if(xmlHttp.status == 200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data; //message equals data between response tags from foodstore.php
document.getElementById("underInput").innerHTML = '<span style="color:blue">' + message + '</span>';
setTimeout('process()', 1000);
}else{
alert('Something went wrong!');
}
}
}
foodstore.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','ham','bacon','chicken');
if(in_array($food, $foodArray))
echo 'We do have ' . $food . '!';
elseif($food == '')
echo 'Enter a food';
else
echo 'Sorry we dont sell ' . $food . '!';
echo '</response>';
?>