2017-01-20 3 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リクエストは、get要求の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); 
} 

は...

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

シンプルにもあなたがcallback(xmlHttp.responseText)を呼んでいるHow does the “this” keyword work?

1

参照してください、そう!

ワン小さな点:.openを呼び出して、いくつかの(古い)のブラウザでイベントハンドラをリセットされますので、私は、onreadystatechange.openコールを置くことをお勧めします。

関連する問題