2013-01-19 94 views
3

可能重複:
How to return the response from an AJAX call from a function?JavaScript函數返回undefined上螢火

我的應用程序的命名空間我剛剛定義的函數:

版本1

window.App = { 
    isLogged: function() { 
    $.get('/user/isLogged', function (data) { 
     if (data == 'true') { 
     return true; 
     } 
     return false; 
    }); 
    } 
}; 

版2

window.App = { 
    isLogged: function() { 
    var test = $.get('/user/isLogged'); 
    console.log(test.responseText); 
    } 
}; 

在第1版,當我嘗試在螢火功能「App.isLogged()」我有一個很好的不確定:S

在2版本,當我嘗試對螢火蟲的功能, responseText的似乎是不確定的:堅持:

我很新約的JavaScript,也許一個範圍問題...

我的函數的目標很明確,我認爲,有一個更好的方式來實現這一目標?

+0

看起來像'/用戶/ isLogged'不存在。它可能來自第一個表示根目錄的'/'。 –

+0

順便說一句,您還可以在版本1中執行'return data =='true''。 –

+0

@ChrisJamesC:不,問題在於Ajax無法以此方式工作。您不能從Ajax回調中返回類似的值(當然,也可能是'/ user/isLogged'不存在,但這是另一個問題)。 –

回答

2

在第一個版本 $.get是異步的,這就是爲什麼你不上第二個版本得到一個返回值

$.get收益遞延對象不具有responseText

window.App = { 
    isLogged: function() { 
    var dfd = $.Deferred(); 
    $.get('/user/isLogged', function (data) { 
     if (data == 'true') { 
     return dfd.resolve(); 
     } 
     return dfd.reject(); 
    }); 
    return dfd.promise(); 
    } 
}; 

$.when(App.isLogged()).then(function() { 
    //your code 
}).fail(function() { 
    //fail code 
}); 
+1

你不必創建自己的延遲對象,你只需返回什麼'。。.get '回報。 –

+0

@Felix Kling肯定你..有很多代碼版本可以工作.. – salexch

+0

哦,等等......如果你在成功回調中進行測試,那麼使用你自己的測試是有意義的。對不起,忽略我的第一條評論。 –