简体   繁体   中英

Javascript function returning session object

This is a simple script to retrieve a 'CouchDB' session and get the user information. It utilizes 'couch.j's which uses 'jQuery'. I've been using JavaScript for a little while but I can't figure out how to pass return values and then use them.

$(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

              }
        }
  });
};

What is stumping me even more is that the console.log statement in the $(document).ready function is returning "undefined" before the console.log statement in the getCtx() function returns. Which means that it isn't giving getCtx() time to execute and actually get the session.

You can move the assignment to the success function of the AJAX call like so

$(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而不是返回值

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM