我正在使用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; }
}
有人能告诉我这里的错误是什么吗?
提前致谢, 纳文
答案 0 :(得分:2)
您正在调用该函数并将响应分配给onreadystatechange,而不是将您的处理程序分配给该事件。它应该是:
ajax.onreadystatechange = ajaxCallback;