我已经定义了以下对象:
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
设置为对象响应值。上面的代码有什么问题?
答案 0 :(得分: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;
});
上下文
类型:PlainObject
此对象将成为所有与Ajax相关的回调的上下文。默认情况下,上下文是一个>对象,表示调用中使用的ajax设置($ .ajaxSettings与设置>合并传递给$ .ajax)。例如,将DOM元素指定为上下文将使>请求的完整回调的上下文,如下所示:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});