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=true、それに設定することを期待しています。users上記のコードで何が間違っていますか?

4

1 に答える 1

2

ajax コールバックで使用するには、オブジェクトへの ajax 呼び出しで context パラメータを設定する必要があります。

    $.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
タイプ: PlainObject
このオブジェクトは、すべての Ajax 関連のコールバックのコンテキストになります。デフォルトでは、コンテキストは、呼び出しで使用される ajax 設定を表すオブジェクトです ($.ajaxSettings が設定とマージされ、$.ajax に渡されます)。たとえば、コンテキストとして DOM 要素を指定すると、次のように、リクエストの完全なコールバックのコンテキストになります。

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