我是AJAX的新手,最近开始做这些在线教程。
链接到youtube上的教程: https://www.youtube.com/watch?v=masMZc3J03I
当我使用教程中的代码时,它工作得很好,但当我更改数组中的值并链接我自己的php文件时,它停止工作。但为什么?代码的结构完全相同。有没有人对此有答案?
以下是教程中的完整代码。
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>
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', 'bacon', 'beef', 'loaf', 'ham');
if(in_array($food, $foodArray))
echo 'We do have ' . $food . '!';
elseif($food=='')
echo 'Enter a food you idiot';
else
echo 'Sorry punk we dont sell no ' . $food . '!'
echo '</response>';
?>
JavaScript的:
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("cant create that object hoss!");
else
return xmlHttp;
}
function process(){
alert("1st checkpoint f(process) - readyState: " + xmlHttp.readyState);//
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
alert("2nd checkpoint f(process) - readyState: " + xmlHttp.readyState);//
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(){
alert("1st checkpoint f(handleServerResponse) - readyState: " + xmlHttp.readyState);//
if(xmlHttp.readyState==4){
alert("2nd checkpoint f(handleServerResponse) - readyState: " + xmlHttp.readyState);//
if(xmlHttp.status==200){
xmlReponse = xmlHttp.responseXML;
xmlDocumentElement = xmlReponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = message;
//setTimeout('process()', 1000);
}else{
alert('Something went wrong!');
}
}
}