【发布时间】:2015-09-02 01:27:33
【问题描述】:
我开始学习 Ajax,我做了这个显示用户输入的简单 HTML 页面,当他键入书名(存储在 php 文件中的数组中),使用 ajax,用户可以在输入下方看到他打字时的结果,这是我无法做到的部分,这是代码:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="bookstore.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body onload="process()">
<h1>
Hadhemi's BookStore !
</h1>
Enter the book you want to order
<input type="text" id="userInput">
<div id="underInput"> </div>
</body>
</html>
这是JS文件
// 3 functions : create an object, communicate and response
var xmlHttp=createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //check for IE
}
catch (e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest(); // ! IE
}
catch (e)
{
xmlHttp = false;
}
}
if (!xmlHttp)
alert("Can't Create that object");
else
return xmlHttp;
}
function process()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
book = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET","book.php?book=" + book,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()',1000);
}
}
function handleServerResponse()
{
//sends back an xml file
if (xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML= message;
setTimeout('process()',1000);
}
else
{
alert("OOps! Something went wrong!");
}
}
}
这是 PHP 文件:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" enconding="UTF-8" standalone="yes" ?>';
echo'<response>';
$book = $_GET['book'];
$bookArray = array('Book1','Book2','Book3');
if(in_array($book, $bookArray))
echo 'We do have'.$book.'!';
elseif ($book='')
echo 'Enter a book name idiot!';
else
echo 'We dont have'.$book.'!';
echo'</response>';
?>
我无法显示 JS 文件应该做什么,有人知道如何解决吗?
编辑:我将所有文件放在 Wamp 下的 www 文件夹中。
【问题讨论】:
-
只是一个建议,如果你现在还在学习过程中,最好使用jquery。有一个 jquery ajax 比这个更容易使用。
-
elseif ($book='')你是在分配而不是比较。 -
是的,我还在学习过程中,感谢您的建议,我会检查 jQuery。
-
@Fred-ii- 我解决了这个问题,但仍然是同样的问题,它只显示 html。
-
请记住
Book1和book1在数组等中并不相同。使用您用于elseif的正确语法更新您的问题,以避免进一步混乱。至于 "除了 html 不显示任何内容" - 你确定 PHP 正在运行和安装吗?您在本地计算机上还是托管?
标签: javascript php html ajax