在javascript中的eventhandler函数中返回?

在javascript中的eventhandler函数中返回?,javascript,xmlhttprequest,Javascript,Xmlhttprequest,以下代码不起作用,并且没有返回正确的结果 function test(file) { var uri = "http://localhost/test.php"; var xhr = new XMLHttpRequest(); var result="done"; xhr.open("POST", uri, true); xhr.send(); xhr.onloadend=function() { result=xhr.responseText; return res

以下代码不起作用,并且没有返回正确的结果

function test(file) {
 var uri = "http://localhost/test.php";
 var xhr = new XMLHttpRequest();
 var result="done";
 xhr.open("POST", uri, true);
 xhr.send();
 xhr.onloadend=function()
  {
   result=xhr.responseText;
   return result;
  }
} 

从事件处理程序返回是错误的,还是只将结果返回到测试函数?

在事件处理程序中返回时,不会将结果返回到调用范围。用于附加侦听器以忽略返回值的DOM事件函数。 如果您试图从onload访问结果,则需要在回调中执行此操作

function test(file, callback){
    var uri = "http://localhost/test.php";  
    var xhr = new XMLHttpRequest();  
    xhr.open("POST", uri, true);  
    xhr.send(formdata);
    xhr.onload=function(){
        callback(xhr.responseText);
    }
}

在事件处理程序中返回时,不会将结果返回到调用范围。用于附加侦听器以忽略返回值的DOM事件函数。 如果您试图从onload访问结果,则需要在回调中执行此操作

function test(file, callback){
    var uri = "http://localhost/test.php";  
    var xhr = new XMLHttpRequest();  
    xhr.open("POST", uri, true);  
    xhr.send(formdata);
    xhr.onload=function(){
        callback(xhr.responseText);
    }
}

从事件处理程序返回是可以的,但是您的返回值并没有到达您显然认为的地方。在大多数情况下,事件处理程序只能返回
true
false
,这表示是否要禁用默认行为(
false
表示“抑制此事件的默认行为”)。无论是在
test()
函数中还是作为
test()
函数的返回值,都无法接收
onloadend
处理程序的返回值,因为事件处理程序是在函数已返回时异步执行的。

可以从事件处理程序返回,但你的回报值并没有达到你显然认为的程度。在大多数情况下,事件处理程序只能返回
true
false
,这表示是否要禁用默认行为(
false
表示“抑制此事件的默认行为”)。无论是在
test()
函数中还是作为
test()
函数的返回值,都无法接收
onloadend
处理程序的返回值,因为事件处理程序是在函数已返回时异步执行的。

一个问题有多个问题?你的问题:14分钟前,一个问题有多个问题?你的问题:就在14分钟前