计算并返回事件处理函数的值

Compute and return value on event handler function

本文关键字:处理函数 事件 返回 计算      更新时间:2023-09-26

我希望从事件处理程序函数存储返回值到变量。

下面是示例代码:
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);
        
    

试试这个:

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