【问题标题】:javascript object method fails to assign ajax call responsejavascript 对象方法无法分配 ajax 调用响应
【发布时间】:2013-03-29 22:37:38
【问题描述】:

我定义了以下对象:

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

【问题讨论】:

  • response 应该返回 JSON 是什么?
  • @icanc 抱歉,我不明白你的问题。

标签: javascript ajax object


【解决方案1】:

您需要在对对象的 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 相关的回调的上下文。默认情况下,上下文是一个 >object,它表示调用中使用的 ajax 设置($.ajaxSettings 与传递给 $.ajax 的设置合并)。例如,指定一个 DOM 元素作为上下文将使该上下文为>请求的完整回调,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2016-04-13
    • 2016-09-10
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多