簡體   English   中英

Javascript函數返回會話對象

[英]Javascript function returning session object

這是一個簡單的腳本,用於檢索“CouchDB”會話並獲取用戶信息。 它使用'couch.j',它使用'jQuery'。 我已經使用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語句返回之前返回“undefined”。 這意味着它沒有給getCtx()時間執行並實際獲得會話。

您可以將賦值移動到AJAX調用的成功函數,就像這樣

$(document).ready(function () {
  getCtx(this);    
});

function getCtx(obj){

     $.couch.session({
        async: false,
        success: function(r) {

              ctx = r.userCtx;
              if (ctx != null){           

                    console.log("returning ctx: "+ctx);   
                    obj.ctx = ctx;                           

              }
        }
  });
};

您需要在成功函數中分配ctx var而不是返回值

嘗試:

$(document).ready(function () {
  var ctx = getCtx();
  console.log(ctx);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM