【问题标题】:AJAX tutorial not workingAJAX 教程不起作用
【发布时间】: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


【解决方案1】:

这是来自 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 !');
    }
}
}

【讨论】:

  • 我收到了 [未捕获的 TypeError: Cannot read property 'documentElement' of null ] 的代码。错误指向 foodstore.js 中的第 41 行,xmlDocumentElement = xmlResponse.documentElement;
  • 帮助很大干杯! Make Sure 检查您是否将 php XML 文件的标头设置为 text/xml 而不是 text/html,就像我不经意间所做的那样
【解决方案2】:

这是我解决问题的方法。

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

如您所见,干净多了!并且做同样的事情:)

【讨论】:

  • 顺便说一句!在运行此代码之前,请确保已包含 jquery :)
  • 如果你要使用它运行,请确保包含该代码: $(document).ready(function() { ... }
【解决方案3】:

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

xmlHttp.onreadystatechange = handleServerResponse();

用这一行:

xmlHttp.onreadystatechange = handleServerResponse;

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

【讨论】:

  • 通过这次更正,它进入了 readyState 4 和状态 200,但由于某种原因,ajax 仍然无法正常工作......
  • 实际上,在我重新设置计时器并刷新页面几次后,它确实开始工作了。谢谢约瑟夫!
【解决方案4】:

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

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 工作!上面的链接中还列出了其他几种解决方法。

【讨论】:

    【解决方案5】:

    确保您正在工作的文件夹在 XAMPP 的 htdocs 文件夹中!

    【讨论】:

      猜你喜欢
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多