0

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

1 回答 1

2

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

DoStuff.getUserToken().done(function(result) {
    // blablabla
}).fail(function(result) {
    // error blablabla
});
于 2013-09-19T18:55:04.353 回答