2017-01-20 211 views
0

試圖讓我的頭繞過http請求和異步JavaScript行爲。Javascript XmlHttpRequest回調

function httpGetAsync(url, callback){ 
    var xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = function() { 
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200){ 
     console.log(xmlHttp.responseText); // prints the ip address 
     callback(xmlHttp.responseText); 
    } 
    } 
    xmlHttp.open("GET", url, true) 
    xmlHttp.send(null); 

} 

httpGetAsync("http://httpbin.org/ip", function(){ 
    console.log(this); // doesn't print the ip address 
}) 

http請求只是一個簡單的返回獲取請求的json格式的ip地址。在函數定義中,IP地址可以很好地打印到控制檯,但是在回調中,控制檯打印出窗口對象。 this可能是使用錯誤的東西,我該如何在回調中訪問xmlHttp.responseText中的數據?

回答

1
callback(xmlHttp.responseText); 

要調用的函數。你正在傳遞一個參數。

function(){ 
    console.log(this); // doesn't print the ip address 
} 

你的功能不期望接收任何參數。改變它,然後使用該參數。

function(my_argument){ 
    console.log(my_argument); 
} 

How does the 「this」 keyword work?

1

你打電話callback(xmlHttp.responseText)見,所以......

httpGetAsync("...", function(response) { 
    console.log(response); 
}); 

簡單!

一小點:我會建議把.open電話onreadystatechange之前,因爲在一些(舊的)的瀏覽器調用.open將重置事件處理程序。