2014-09-03 64 views
0

我有以下功能:变量不会得到在Ajax的功能,正确的价值

function sendDocument(objektnummer, id) 
{ 
    var url = $("#objectdata").data("url-send"); 
    var data = {}; 
    data["objektnummer"] = objektnummer; 
    data["id"]    = parseInt(id); 

    var result = false; 
    $.ajax({ 
     type: "POST", 
     url: url, 
     data: data, 
     dataType: "json" 
    }) 
     .done(function(resp){ 
      console.log("send ajax was successfull"); 
      result = true; 
     }) 
     .error(function(resp){ 
      console.log("no connection"); 
      result = false; 
     }); 
    console.log(result); 
    return result; 
} 

在我得到了积极的信息“发送AJAX是成功的”控制台,但是当我在打印出结果该函数结束后,我看到变量结果的值为false

+2

当阿贾克斯操作是异步的,您不能从一个函数返回值。该函数在设置'return = true'之前返回。传递回调,或者返回Ajax对象(这是一个jQuery'promise')。 – 2014-09-03 10:09:36

回答

1

当Ajax操作是异步时,不能从函数返回值。该功能在设置return = true之前很久就会返回。传递回调,或者返回Ajax对象(这是一个jQuery promise)。

回调版本:

function sendDocument(objektnummer, id, callMeWhenDone) 
{ 
    var url = $("#objectdata").data("url-send"); 
    var data = {}; 
    data["objektnummer"] = objektnummer; 
    data["id"]    = parseInt(id); 

    $.ajax({ 
     type: "POST", 
     url: url, 
     data: data, 
     dataType: "json" 
    }) 
     .done(function(resp){ 
      console.log("send ajax was successfull"); 
      callMeWhenDone(true); 
     }) 
     .error(function(resp){ 
      console.log("no connection"); 
      callMeWhenDone(false); 
     }); 
} 

调用具有回调:

sendDocument(objektnummer, id, function(success){ 
     if (success){ 
      // Do this! 
     } 
}); 

一个promise版本在这种情况下看起来像:

function sendDocument(objektnummer, id) 
{ 
    var url = $("#objectdata").data("url-send"); 
    var data = {}; 
    data["objektnummer"] = objektnummer; 
    data["id"]    = parseInt(id); 

    return $.ajax({ 
     type: "POST", 
     url: url, 
     data: data, 
     dataType: "json" 
    }) 
     .done(function(resp){ 
      console.log("send ajax was successfull"); 
     }) 
     .error(function(resp){ 
      console.log("no connection"); 
     }); 
} 

而且会被称为是这样的:

sendDocument(objektnummer, id).done(function(){ 
     // Do this! 
}).fail(function(){ 
     // Something went wrong! 
}); 

有了承诺,可以为事件注册任意次数(所以它比回调考虑更灵活)