javascript对象方法无法分配ajax调用响应

标签 javascript ajax object

我定义了以下对象:

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;
    });

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");
});

关于javascript对象方法无法分配ajax调用响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15712482/

相关文章:

ajax - jQuery AJAX 请求错误状态 0

javascript - 如何从控制台查看或输出很长的字符串

javascript - 使用 XMLHttpRequest 为 RGB 图像生成主色

javascript - 点击位置 <div> 标签

用于匹配数组中数字的 JavaScript 正则表达式

java - 如何在ajax中发送多部分/表单数据请求

python - 是否可以使用 AJAX 更改查询集?

python - 通用函数/对象加倍装饰器在 Python 中是否可行?

arrays - 通过 json2typescript 反序列化 json 时出错

Javascript Canvas 高分故障