这是 html 程序...这里我使用 ajax 在文本字段上输入一些数据后显示输出,当 food='' 时它只给出第一个响应,之后它不会显示另一个像我们没有的响应。或者我们确实有。
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h1>choose your favorite food</h1>
<input type="text" id="inputuser">
<div id="usererror"></div>
</body>
</html>
这是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('shahi paneer','matar paneer','matar alu','raita');
if(in_array($food,$foodArray))
{
echo 'we do have '.$food.'!';
}
elseif($food=='')
{
echo 'please enter any dish';
}
else
{
echo 'we dont have '.$food.'!';
}
echo '</response>';
?>
这是 foodstore.js
var xmlHttp=createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if (window.XMLHttpRequest)
{
xmlHttp=new XMLHttpRequest();
}
else
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlHttp)
alert("cant create that object");
else
return xmlHttp;
}
function process()
{
if (xmlHttp.readyState==0 ||xmlHttp.readystate==4)
{
dish=encodeURIComponent(document.getElementById("inputuser").value);
xmlHttp.open("GET","foodstore.php?food="+dish, true);
xmlHttp.onreadystatechange=handleServerResponse;
xmlHttp.send(null);
}
else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse=xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message=xmlDocumentElement.firstChild.data;
document.getElementById("usererror").innerHTML='<span style ="color:red">'+message+'</span>';
setTimeout('process()',1000);
}
else
{
alert('something went wrong');
}
}
}