試圖讓我的頭繞過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
中的數據?