gpt4 book ai didi

Javascript 对象和 jQuery AJAX

转载 作者:行者123 更新时间:2023-12-02 18:20:12 24 4
gpt4 key购买 nike

我创建了一个 JavaScript 对象,我正在尝试执行 jQuery AJAX 请求并根据响应在对象中设置一个变量,但它不起作用。该变量返回空。这是代码...

$(document).ready(function() {

var DoStuff = {

clientToken : null,
userToken: null,

init : function() {
this.getUserToken();
},

setClientToken : function(token) {
this.clientToken = token;
this.init();
},

getUserToken : function() {


$this = this;

var request = $.ajax({
url: "/api/user/current_user/",
type: "POST",
data: { clientToken : this.clientToken },
dataType: "json"
});

request.done(function(response) {
if(response.userToken) {
/* this should be setting the DoStuff.userToken variable */
$this.userToken = response.userToken;
}else {
$this.userToken = "didn't work :(";
}
});

},

setUserToken : function(token) {
this.userToken = token;
},

showUserToken : function() {

alert(this.userToken);

}

};

//-> Set the client all requests will be sent on behalf of
DoStuff.setClientToken("clienttokenherewooo");
DoStuff.showUserToken(); // this should show the value the AJAX returned, but it's empty
});

最佳答案

AJAX 是异步的。在函数 getUserToken 返回 ajax 对象并执行类似的操作:

DoStuff.getUserToken().done(function(result) {
// blablabla
}).fail(function(result) {
// error blablabla
});

关于Javascript 对象和 jQuery AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18902438/

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