這是一個簡單的腳本來檢索'CouchDB'會話並獲取用戶信息。它利用'couch.j'使用'jQuery'。我一直在使用JavaScript一段時間,但我無法弄清楚如何傳遞返回值然後使用它們。Javascript函數返回會話對象
$(document).ready(function() {
this.ctx = getCtx(); //it doesn’t appear that this is actually assigning a variable
console.log(this.ctx); //this returns 「undefined」
});
function getCtx(){
$.couch.session({
async: false,
success: function(r) {
ctx = r.userCtx;
if (ctx != null){ //I added this check because otherwise ctx was returning undefined.
console.log("returning ctx: "+ctx);
//Log says: returning ctx: [object Object]
return ctx;
//I know this is returning an object, because of the line above
}
}
});
};
是什麼絆倒了我更是在$(document).ready
功能的console.log語句在getCtx()
函數返回的console.log語句之前返回「不確定」。這意味着它不會給getCtx()
時間執行並實際獲得會話。
你需要成功的函數來設置getCtx函數中的局部變量,以便它可以返回它,你getCtx當前不返回任何東西。 – Dampsquid 2012-02-23 22:07:52