AJAX教程无法正常工作

时间:2014-09-01 03:27:16

标签: javascript php ajax

我正在关注Bucky's (the new boston) tutorial on Ajax并且在第一课='

时卡住了

以下是我的问题:

Ajax不能正常工作。我在.js上设置了一些检查点警报,发现“readyState”从未命中4 - 我只收到3个警报:

  • f(进程)第一个检查点 - readyState:0
  • f(进程)第二检查点 - 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!');
        }
    }
}

任何帮助表示赞赏!

5 个答案:

答案 0 :(得分:5)

这是来自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>

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','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 !');
    }
}
}

答案 1 :(得分:3)

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

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

你可以看到更清洁!并做同样的事情:))

答案 2 :(得分:2)

在foodstore.js中,在process()内部,替换这一行:

xmlHttp.onreadystatechange = handleServerResponse();

这一行:

xmlHttp.onreadystatechange = handleServerResponse;

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

答案 3 :(得分:1)

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

alert('Someting went wrong !');

到此:

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

我注意到我的状态始终为0,所以我查看了我的控制台并得到了这个错误:

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

调查此错误后,我找到this answer to a similar problem

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

答案 4 :(得分:0)

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