【问题标题】:xmlhttp is undefined. Javascript Ajaxxmlhttp 未定义。 Javascript Ajax
【发布时间】:2014-02-07 23:57:53
【问题描述】:

我是 javascript 的新手,尤其是 ajax.. 只是想弄清楚..

我从一个教程中编写了这段代码,但找不到我做错了什么。 Here you can see it live

我从 Firebug 得到的错误:“TypeError: xmlhttp is undefined [打破这个错误]

if (xmlhttp.readyState == 4){"

我的代码是

// JavaScript Document

var xmlhttp;
var url;

function ajaxFunction(){

if  (window.ActiveXObject){//if the window is InternetExplorer

    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    }else if(window.XMLHttpRequest){// if Window is Firefox etc..

        xmmlhttp= new XMLHttpRequest();

        }else{

            alert ("Get a New Browser")

            }

}//end of ajaxFunction()


function getInfo(){

    ajaxFunction();

    var entryInfo= document.getElementById("entry").value;

            function stateChanged(){
                if (xmlhttp.readyState == 4){

                    document.getElementById("results").innerHTML = xmlhttp.responseText;

                    }//if (xmlhttp.readyState == 4)

                }//end of function stateChanged()


url = "info.php?user="+entryInfo;
xmlhttp.onreadystateshange=stateChanged();
xmlhttp.open("GET",url,true);
xmlhttp.send(null);


    }// end of function getInfo

【问题讨论】:

  • 您的onreadystatechange 属性应该是对没有() 的函数的引用,而不是像xmlhttp.onreadystateshange = stateChanged; 中那样带有() 的函数调用

标签: javascript ajax


【解决方案1】:

这里有错别字:

   xmmlhttp= new XMLHttpRequest();
     ^

改成

 xmlhttp= new XMLHttpRequest();

正如 Michael 指出的,在分配 onreadystatechange 函数时有括号:

xmlhttp.onreadystateshange=stateChanged();
                                       ^ remove the ()

如果不去掉括号,会调用stateChange()函数,返回值给xmlhttp.onreadystateshange,这是你不想要的。

【讨论】:

    【解决方案2】:

    属性名称有误: xmlhttp.onreadystateshange=stateChanged;

    必须是'onreadystatechange'

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多