-1

我正在用 javascript 演示做一个非常简单的 AJAX。我的应用程序有一个 AddCountry 页面,用户选择一个国家,状态列表通过 AJAX 动态填充。

演示运行良好,直到我决定尝试新的东西。我没有使用事件处理程序的匿名回调onreadystatechange,而是使用了命名回调。它给了我这个错误:

Uncaught InvalidStateError: Failed to read the 'status' property from 'XMLHttpRequest': the object's state must not be OPENED. 

下面是两个示例代码:

共同部分:

<script type="text/javascript">
   function createXHR(){
       if(window.XMLHttpRequest)
           return new XMLHttpRequest();
       else 
           return new ActiveXObject("MSXML2.XMLHTTP");
   }

   function getStates()
   {
       alert("inside getStates");
       var ajax = createXHR(); // step 1 : create XHR object
       alert("XHR:"+ajax);
       // step 2: creating the ajax request
       var inputVal = document.getElementById("country"); 
       var country = inputVal.value;
       alert("Value:"+country);
       ajax.open("GET","index.jsp?country="+country, true);  

       // sending the ajax request
       ajax.send(null);

       // step 4: monitoring for and updating the response

之后,此代码不起作用:

ajax.onreadystatechange = ajaxCallback();
         function ajaxCallback(){
             //alert("Response Received:"+ajax.status);

               if (ajax.status === 404)
                   alert("status 404");

               if (ajax.readyState === 4 && ajax.status === 404)
               { 
                   alert("Response Received; "+ajax.responseText);
                   document.getElementById("states").innerHTML = ajax.responseText; 
               }
          }

但这有效:

ajax.onreadystatechange = function (){
    if (ajax.readyState == 4 && ajax.status == 200)
    { document.getElementById("states").innerHTML = ajax.responseText; }
}

谁能让我知道这里的错误是什么?

提前致谢, 纳文

4

1 回答 1

2

您正在调用该函数并将响应分配给 onreadystatechange,而不是将您的处理程序分配给事件。它应该是:

ajax.onreadystatechange = ajaxCallback;

于 2013-11-29T07:48:40.797 回答