Javascript对象方法分配ajax调用响应失败

javascript object method fails to assign ajax call response

本文关键字:调用 响应 失败 ajax 分配 对象 方法 Javascript      更新时间:2023-09-26

我已经定义了以下对象:

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设置为对象响应值。上面的代码有什么问题?

您需要在ajax调用中设置对象的上下文参数,以便在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;
    });

上下文类型:PlainObject
这个对象将成为所有ajax相关回调的上下文。默认情况下,上下文是一个>对象,表示调用($. js)时使用的ajax设置。ajaxSettings与设置合并>传递到$.ajax)。例如,指定DOM元素作为上下文将使>的上下文成为请求的完整回调,如下所示:

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});