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リクエストは、get要求のjsonフォーマットIPアドレスを返す単純なものです。関数定義ではIPアドレスをコンソールに出力することはできますが、コールバックではコンソールがウィンドウオブジェクトを出力します。 this
は、私がコールバックでxmlHttp.responseText
内のデータにアクセスできますどのように、おそらく使用する間違ったことありますか?