1

我定义了以下对象:

var WealthyLaughingDuckControl = {
    initialised: false,
    users: [],
    fetchData: function() {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "../php/client/json.php",
            data: {
                type: "users"
            }
        }).done(function(response) {
            this.initialised = true;
            this.users = response;
        });
    },
    init: function() {
        if (!this.initialised) {
            this.fetchData();
        }
    },
    getData: function() {
        return this.users;
    }
};

我正在浏览器 javascript 控制台中调试此对象。执行前后对象的状态是一样的WealthyLaughingDuckControl.init()

Object {initialised: false, users: Array[0], fetchData: function, init: function, getData: function}

但是,我确信 ajax 响应可以正常工作,因为当我执行以下操作时:

        $.ajax({
            type: "GET",
            dataType: "json",
            url: "../php/client/json.php",
            data: {
                type: "users"
            }
        }).done(function(response) {
            alert(response);
        });

浏览器提醒我[Object object]。所以我希望对象具有initialised=trueusers设置为对象响应值。上面的代码有什么问题?

4

1 回答 1

2

您需要在对对象的 ajax 调用中设置 context 参数,以便在 ajax 回调中使用它。

    $.ajax({
        type: "GET",
        dataType: "json",
        context: this,
        url: "../php/client/json.php",
        data: {
            type: "users"
        }
    }).done(function(response) {
        this.initialised = true;
        this.users = response;
    });

context
Type: PlainObject
This object will be made the context of all Ajax-related callbacks. By default, the context is an >object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings >passed to $.ajax). For example, specifying a DOM element as the context will make that the context for >the complete callback of a request, like so:

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});
于 2013-03-29T22:49:17.823 回答