我创建了一个 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
});