0

I am looking to store a returned value to a variable from the event handler function.

Here is the example code:

var xhr = new XMLHttpRequest();
    
    function getData(e){
            if(xhr.readyState === 4){
            if(xhr.status === 200){
                e = JSON.parse(xhr.response);
                return e;   
            }
            else{
                return alert("Error!!");
            }
        }
    }
      
   var data;
   xhr.addEventListener("load", function(){getData(data);},true);  // want to store the result to data variable
   console.log(data);
        
    
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Faraz_pk
  • 53
  • 5
  • You can in fact return a value from `getData`, however it is impossible to return that value to the outer scope because the outerscope has already returned. – Kevin B Oct 21 '15 at 15:11

1 Answers1

-1

Try this:

xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
    //function to return your value function(xhr.responseText)
}
};