AJAX教程不起作用


AJAX tutorial not working

我一直在学习Bucky(新波士顿)关于Ajax的教程,但在第一节课上就被卡住了=|

这是我的问题:

Ajax不起作用。我在.js上设置了一些检查点警报,发现"readyState"从未达到4-我只得到3个警报:

  • f(进程)第一个检查点-readyState:0
  • f(进程)第二个检查点-readyState:0
  • f(handleServerResponse)第一个检查点-readyState:1

我使用Xampp在本地主机上运行,浏览器有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!');
        }
    }
}

感谢您的帮助!

这是来自Bucky的AJAX教程。如果你感兴趣的话,这里有完整的工作代码:

index.html

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
    <h3>The Chuff Bucker</h3>
    Enter the food you would like to order:
    <input type="text" id="userInput" />
    <div id="underInput" />
</body>
</html>

食品商店.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.'!';
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 !")
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);//cekaj 1s pa probaj opet
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){ 
    if(xmlHttp.status==200){
        xmlResponse = xmlHttp.responseXML; //izvlaci se xml sto smo dobili
        xmlDocumentElement = xmlResponse.documentElement;
        message = xmlDocumentElement.firstChild.data;
        document.getElementById("underInput").innerHTML = message;
        setTimeout('process()', 1000);
    }else{
        alert('Someting went wrong !');
    }
}
}

以下是我如何处理这个问题。

var userInput = $("#userInput").val();
$.ajax({
   url: 'foodstore.php',
   data: userInput,
   method: 'GET',
   success: function(response){
       $("#underInput").html(response);
   }
});

正如你所看到的,干净多了!并执行相同的操作:)

在foodstore.js中,在process()中,替换此行:

xmlHttp.onreadystatechange = handleServerResponse();

这行:

xmlHttp.onreadystatechange = handleServerResponse;

这是因为您传递的是函数本身,而不是函数调用后的返回值。看见http://www.reddit.com/r/learnprogramming/comments/24iqej/javascriptjquery_why_are_parentheses_not_always/

当我遇到这个问题时,我更改了这行

alert('Someting went wrong !');

到此:

alert('Someting went wrong ! readyState = ' + xmlHttp.readyState + ', Status = ' + xmlHttp.status);

我注意到我的状态总是0,所以我在控制台上查看了一下,得到了这个错误:

XMLHttpRequest cannot load file: foodstore.php?food="+food

通过调查这个错误,我发现了类似问题的答案。

基本上,我的浏览器出于安全原因阻止了我的XMLHttpRequest请求。我上传这些文件(+错误修复)到个人网络服务器和AJAX工作!上面的链接中还列出了其他几种解决方法。

确保您正在使用的文件夹位于XAMPP的htdocs文件夹中!