gpt4 book ai didi

Javascript 函数返回 session 对象

转载 作者:行者123 更新时间:2023-11-30 13:23:20 25 4
gpt4 key购买 nike

这是一个简单的脚本,用于检索“CouchDB” session 并获取用户信息。它利用使用“jQuery”的“couch.j”。我已经使用 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( ) 函数返回。这意味着它没有给 getCtx() 时间来执行并实际获取 session 。

最佳答案

您可以像这样将赋值移动到 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;

}
}
});
};

关于Javascript 函数返回 session 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9422052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com