我是ajax的新手,并且正在遵循youtube教程来创建简单的食物搜索应用用户在输入字段中输入食物名称的地方,在其他地方显示名称说没有食物但以某种方式无法在Wamp Server上运行。
这是我的代码
index.html
<!Doctype html> <html lang = "en"> <head> <title>Ajax app</title> <meta charset = "UTF-8"> <style> </style> <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"></div> </body> </html>
foodstore.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 boss"); }else{ return xmlHttp; } } function process() { if(xmlHttp.readyState==0||xmlHttp.readyState==4){ 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() { //readystate 4 whenever response is ready and object done communicating if(xmlHttp.readyState==4){ //state 200 means communiaction went ok if(xmlHttp.readyState==200){ xmlResponse = xmlHttp.responseXML; xmlDocumentElement = xmlResponse.documentElement; message = xmlDocumentElement.firstChild.data; 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","bacon","beef","loaf","ham"); if(in_array($food,$foodArray)) { echo "We do have" .$food. "!"; } elseif($food ="") { echo "Enter a food please."; } else { echo"sorry but we don't even sell" . $food. "!"; } echo "</response>"; ?>
任何帮助将不胜感激,谢谢
我是ajax的新手,并且正在遵循youtube教程来创建一个简单的食物搜索应用程序,用户可以在输入字段中输入食物名称,它在下面显示名称,否则表示食物不可用,但...
请执行不要