我刚刚开始学习Ajax,并观看了有关如何编写少量输入的教程,该输入可以检查食品店是否有库存或没有库存。
我已经多次检查了代码,但仍然无法执行任何操作。如果有人可以在这里帮助我,我将感到非常高兴。
该代码基本上是三个文件:
Index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The Food Store</h3>
<p>Enter the food you would like to have:</p>
<input type="text" id="userInput">
<div id="underInput"/>
</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('tuna', 'bacon', 'beef', 'ham');
if(in_array($food,$foodArray)) {
echo 'We do have '.$food'!';
echo '</response>';
}
}
?>
最后是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("Cant create that object!");
else {
return xmlHttp;
}
}
// This is now the communication part!
function process() {
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
food = encodeURIComponent(document.getElmentById("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){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = '<span styel="color:blue">' + message + '</span>';
setTimeout('process()',1000);
}else{
alter('Something went wrong!');
}
}
}
我真的很感谢您的帮助。我还在youtube-comments中读到,就js部分而言,jQuery会更易于使用。真的吗?
非常感谢!
最佳答案
是的,它的真正jquery非常容易在这里检查
jquery official site
basic from w3schools