Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
返回会话对象的Javascript函数_Javascript_Jquery_Couchdb - Fatal编程技术网

返回会话对象的Javascript函数

返回会话对象的Javascript函数,javascript,jquery,couchdb,Javascript,Jquery,Couchdb,这是一个检索“CouchDB”会话并获取用户信息的简单脚本。它使用'coach.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 r

这是一个检索“CouchDB”会话并获取用户信息的简单脚本。它使用'coach.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”。这意味着它没有给执行和实际获取会话的时间。

尝试:

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

您需要在success函数中分配ctx var,而不是返回值,您可以将分配移动到AJAX调用的success函数,如下所示

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

              }
        }
  });
};

您需要success函数在getCtx函数中设置一个本地变量,这样它就可以返回它,而getCtx current不会返回任何内容。因此,我尝试按照您的建议执行,但是如果我向$(document)添加任何其他内容。ready函数,它们会尝试在getCtx(this);)之前执行;。例如,如果我放置一个“console.log(this.ctx);”“getCtx(this);”之后的语句输出将是两个日志,一个“未定义”,然后一个“返回ctx:[对象]”。这似乎与JavaScript编译/解释的工作顺序有关,但我不理解。