AJAX中HTTP对象的清洁语法?

时间:2013-09-14 22:42:19

标签: javascript ajax html5 callback

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();
}

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:1)

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

将您的回调更改为使用this

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