输入字段被提供给用户,在那里他键入他想要的内容。 Javascript在后台运行以检查用户键入的项目是什么。 这是使用Ajax完成的。
ajaxHtml.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="foodstore.js"></script>
<title>Let's Go</title>
</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();
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 bro!");
}
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(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==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 item';
else
echo 'Sorry we do not sell '.$food.'!';
echo '</response>';
?>
然而,这似乎与WebStorm无关,并且在HTML文件中显示错误。当我在WAMP上运行它时,它运行得很好但是我想知道为什么它在WebStorm IDE上不起作用并且想要找到它的解决方案。