簡體   English   中英

XMLHttpRequest異步讀取,如何不使用匿名函數?

[英]XMLHttpRequest asynchronous read, how not to use anonymous function?

在Google搜索示例后,我發現的所有示例都使用匿名函數,如下所示。 但是我想避免它,因為它會使代碼變得復雜。

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嗎? 有沒有更好的辦法?

您可以將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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM