2017-08-25 56 views
0

在Google搜索示例之后,我发现所有示例都使用匿名函数,如下所示。但我想避免它,因为它使代码变得复杂。XMLHttpRequest异步读取,如何不使用匿名函数?

var xhr = new XMLHttpRequest(), 
    method = "GET", 
    url = "https://developer.mozilla.org/"; 

xhr.open(method, url, true); 
xhr.onreadystatechange = function() { 
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { 
    console.log(xhr.responseText); 
    } 
}; 
xhr.send(); 

如果我想这样做,我该如何传递请求或响应?

function startRequest() 
{ 
    var xhr = new XMLHttpRequest(), 
     method = "GET", 
     url = "https://developer.mozilla.org/"; 

    xhr.open(method, url, true); 
    xhr.onreadystatechange = myhandler; 
    xhr.send(); 
} 

function myhandler() 
{ 
    //how to get xhr here? 
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) 
    { 
    console.log(xhr.responseText); 
    } 
} 

我对静态类型语言比较熟悉,所以JavaScript很混乱。我试图查看onreadystatechange的签名(输入参数),但文档页面没有提及它。似乎动态类型语言(Python,PHP)的文档往往不会正式描述输入参数,所以我不得不猜测这些方法需要什么类型的参数。

它没有参数,我应该使用全局变量将请求和响应传递给myhandler?有没有更好的办法?

+2

使用'this'。它将引用请求对象。 (因为'myHandler'是作为请求的状态改变事件监听器传递的)。 –

+0

您也可以将'myHandler'定义放入'startRequest'中,然后它将在变量的范围内。 – Barmar

回答

1

您可以将xhr对象传递给包含响应对象的处理程序。

function startRequest() 
{ 
    var xhr = new XMLHttpRequest(), 
     method = "GET", 
     url = "https://stackoverflow.com/questions/45887959/xmlhttprequest-asynchronous-read-how-not-to-use-anonymous-function"; 

    xhr.open(method, url, true); 
    xhr.onreadystatechange = myhandler(xhr); 
    xhr.send(); 

} 

function myhandler(xhr) 
{ 
    //how to get xhr here? 
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) 
    { 
    console.log(xhr.responseText); 
    }else if(xhr.status===0){ 
     console.log(xhr.responseText); 
    } 
} 

startRequest();