我開始學習Ajax,並且做了這個簡單的HTML頁面,當他鍵入一本書的名字(存儲在php文件中的一個數組中)時,使用ajax,用戶可以看到輸入下面的結果,而他的類型,這是我無法做到的部分,下面的代碼:簡單的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比這個更容易使用。 – Hope
'elseif($ book ='')'你正在分配而不是比較。 –
是的,我仍然在學習過程中,並感謝您的建議,我會檢查jQuery。 – Hadh