1

AJAX noob here...所以下面的这段代码适用于我,它在 onclick 事件期间被调用:

function updateText() {
  var http = getHTTPObject();    
  http.open("GET","ajax_info.asp",true);
  http.onreadystatechange = function() {
    if (http.readyState == 4) {
      document.getElementById("myDiv").innerHTML=http.responseText; 
    }
  }
  http.send();      
}

但是,当我尝试像下面这样清洁它时,它不再起作用。下面的代码不是正确的回调语法吗?

function handleHTTPResponse() {
  if (http.readyState == 4) {
    document.getElementById("myDiv").innerHTML=http.responseText;
  }
}

function updateText() {
  var http = getHTTPObject();    
  http.open("GET","ajax_info.asp",true);           
  http.onreadystatechange = handleHTTPResponse;
  http.send();
}
4

2 回答 2

2

该函数handleHTTPResponse()不知道http变量是什么。在其范围内没有使用该名称声明的变量。

将其作为参数传入

function handleHTTPResponse(http) {
    if (http.readyState == 4) {
        document.getElementById("myDiv").innerHTML=http.responseText;
    }
}

...

http.onreadystatechange = function() { handleHTTPResponse(http) };

或者,正如@dc5 在另一个答案中指出的那样,使用this

http.onreadystatechange = function() { handleHTTPResponse(this) };

或等效且更清洁

function handleHTTPResponse() {
    if (this.readyState == 4) {
        document.getElementById("myDiv").innerHTML=this.responseText;
    }
}

...

http.onreadystatechange = handleHTTPResponse;

或者,将函数放在范围内,以便它可以“看到”http

function updateText() {

    function handleHTTPResponse() {
        if (http.readyState == 4) {
            document.getElementById("myDiv").innerHTML=http.responseText;
        }
    }

    var http = getHTTPObject();    
    http.open("GET","ajax_info.asp",true);           
    http.onreadystatechange = handleHTTPResponse;
    http.send();
}

或者,使http全局

var http;    

function handleHTTPResponse() {
    if (http.readyState == 4) {
        document.getElementById("myDiv").innerHTML=http.responseText;
    }
}

function updateText() {
    http = getHTTPObject();    
    http.open("GET","ajax_info.asp",true);           
    http.onreadystatechange = handleHTTPResponse;
    http.send();
}
于 2013-09-14T22:46:02.397 回答
1

您的回调无权访问变量http,但是,在调用时,它的上下文是变量引用的值。

将您的回调更改为使用this

function handleHTTPResponse() {
    if (this.readyState == 4) {
        document.getElementById("myDiv").innerHTML=this.responseText;
    }
}
于 2013-09-14T22:50:13.223 回答