【发布时间】:2014-10-25 05:56:35
【问题描述】:
我关注了Bucky's (the new boston) tutorial on Ajax,但在第一课就卡住了=|
这是我的问题:
Ajax 不工作。我在 .js 上设置了一些检查点警报,发现“readyState”从未达到 4 - 我只收到 3 个警报:
- f(process) 第一个检查点 - readyState: 0
- f(process) 第二个检查点 - readyState: 0
- f(handleServerResponse) 第一个检查点 - readyState: 1
我使用 Xampp 在 localhost 上运行,浏览器是 Chrome 和 Firefox。
代码如下:
index.html:
<!DOCTYPE html>
<html>
<head>
<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" />
</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', 'loaf', 'ham');
if(in_array($food, $foodArray))
echo 'We do have ' . $food . '!';
elseif($food=='')
echo 'Enter a food you idiot';
else
echo 'Sorry punk we dont sell no ' . $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 hoss!");
else
return xmlHttp;
}
function process(){
alert("1st checkpoint f(process) - readyState: " + xmlHttp.readyState);//
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
alert("2nd checkpoint f(process) - readyState: " + xmlHttp.readyState);//
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(){
alert("1st checkpoint f(handleServerResponse) - readyState: " + xmlHttp.readyState);//
if(xmlHttp.readyState==4){
alert("2nd checkpoint f(handleServerResponse) - readyState: " + xmlHttp.readyState);//
if(xmlHttp.status==200){
xmlReponse = xmlHttp.responseXML;
xmlDocumentElement = xmlReponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = message;
//setTimeout('process()', 1000);
}else{
alert('Something went wrong!');
}
}
}
任何帮助表示赞赏!
【问题讨论】:
-
你有没有想过用jQuery来代替?
-
第一个问题是
xmlHttp.onreadystatechange = handleServerResponse();..你需要给statechange分配一个函数引用不要调用函数xmlHttp.onreadystatechange = handleServerResponse; -
@zsawaf 是的,我做到了,但没有成功。实际上我已经尝试了一切,本教程是我最后的手段......我已经被 Ajax 困了好几天了。
-
您正试图在
onload处理程序中读取userInput的值...它是空的...您可能想要使用点击处理程序?
标签: javascript php ajax